如何使用 C 中的二进制搜索计算数组中重复项的出现次数?

How to count occurrences of duplicates in array using binary search in C?

我必须在 C 中使用二进制搜索计算数组中某个元素的出现次数。 我写了下面的代码但是当我用来输入时
那么输出是错误的。我也尝试过预定义数组中的元素并使用此代码并且它工作正常。但是当我使用 scanf 语句提供自定义输入时,程序不会省略正确的答案。我已经用 C 实现了好几个小时了。任何 help/suggestions 将不胜感激。

#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;
}


您不能使用二进制搜索来定位未排序数组中的数据。对于二进制搜索工作,元素必须按递增顺序排列。可以在程序中使用'qsort'对数组进行排序,或者修改要排序的输入

如果将输入数组修改为:[1 4 5 5 7],输出将为:2