我想找出一个元素在排序数组中出现的次数。我使用 BinarySearch 逻辑来实现它。但我没有得到正确的输出。我正在使用这个逻辑
numberOfOccurrence = findLastOccurrence - firstOccurrence + 1
这是我的代码
#include<stdio.h>
int find_last(int a[],int n,int key)
{
int low = 0;
int high = n-1;
int result = -1;
while(low<=high)
{
int mid = (low+high)/2;
if(a[mid]==key)
{
result = mid;
low = mid+1;
}
else if(key<a[mid])
high = mid-1;
else
low = mid+1;
}
return result;
}
int find_first(int a[],int n,int key)
{
int low = 0;
int high = n-1;
int result = -1;
while(low<=high)
{
int mid = (low+high)/2;
if(a[mid]==key)
{
result = mid;
high = mid-1;
}
else if(key<a[mid])
high = mid-1;
else
low = mid+1;
}
return result;
}
int find_count(int a[],int n,int x)
{
int first,last;
first = find_first(a,n,x);
last = find_last(a,n,x);
printf("\nLast index is %d",last+1);
printf("\nFirst index is %d",first+1);
printf("\nlast-first+1 is %d",last - first + 1);
return (last-first+1);
}
main()
{
int a[10],flag=0,n,x,count=0,i;
printf("\nEnter the number of elements ");
scanf("%d",&n);
printf("\nEnter %d elements ",n);
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("\n Elements are \n");
for(i=0;i<n;i++){
printf("%d ",a[i]);
}
printf("\n Enter the key ");
scanf("%d",&x);
count = find_count(a,n,x);
printf("%d","\n The count is %d \n",count);
}
但是语句return (last-first+1);
中有些问题。它正在返回一些大值。
我在 CFree 中使用 mingw 和 Visual Studio 2010 进行了测试。
最佳答案
printf("%d","\n The count is %d \n",count);
将其更改为:
printf(" The count is %d \n",count);
你不能在 printf 中放置多个 ""
关于c - 排序数组中元素出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30444893/