【问题标题】:How to count occurrences of duplicates in array using binary search in C?如何使用C中的二进制搜索计算数组中重复项的出现次数?
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 我是在对数组进行排序后得到的。非常感谢您的帮助。
猜你喜欢
  • 2022-07-07
  • 2012-11-18
  • 2021-06-11
  • 2012-07-23
  • 2021-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-30
相关资源
最近更新 更多