【发布时间】:2020-12-05 20:14:34
【问题描述】:
我必须使用 C 中的二进制搜索来计算数组中某个元素的出现次数。
我已经编写了以下代码,但是当我使用输入时
那么输出是错误的。我还尝试预定义数组中的元素并使用此代码,它工作正常。但是当我使用 scanf 语句提供自定义输入时,程序不会省略正确的答案。我已经用 C 实现了几个小时了。任何帮助/建议将不胜感激。
#include <stdio.h>
int fun(int array[], int s, int x, int key)
{
int ss = 0, e = s - 1;
int n = -1;
while (ss <= e)
{
int middle = (ss + e)/2;
if (x == array[middle]){
n = middle;
if (key){
e = middle - 1;
}
else{
ss = middle + 1;
}
}
else if (x < array[middle]){
e = middle - 1;
}
else{
ss = middle + 1;
}
}
return n;
}
int main()
{
int s;
scanf("%d",&s);
int array[s];
for(int i = 0 ; i<s ; i++){
scanf("%d",&array[i]);
}
for(int i = 0 ; i<s;i++){
printf("%d ",array[i]);
}
printf("\n");
int x;
scanf("%d",&x);
int f = fun(array, s, x, 1);
int l = fun(array, s, x, 0);
int t = l - f + 1;
if (f!= -1){
printf("%d ", t);
}
return 0;
}
【问题讨论】:
-
如果您分享失败的输入和预期的输出将会有所帮助
-
@dash-o 我的输入是:5 5 5 4 1 7 5
-
@V_Srj 首先对数组进行排序,然后进行二进制搜索。
标签: arrays c search binary-search