我想找到排序数组中元素的出现次数。我使用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);
中有些问题。它返回了一些大的值。
我在使用mingw和Visual Studio 2010的CFree中进行了测试。
答案 0 :(得分:1)
printf("%d","\n The count is %d \n",count);
将其更改为:
printf(" The count is %d \n",count);
你不能在printf
中放置多个“”答案 1 :(得分:0)
你甚至不需要二元搜索(在任何情况下都需要对数组进行排序)。无论是否对数组进行排序,都需要对数组进行简单的遍历。加上一个小错误检查好的形式(GIGO),这使得这个程序看起来比没有它更笨重。代码的关键部分只有3行。
#include<stdio.h>
#define NUMBERS 10
int main ( ) {
int a[NUMBERS], n, x, count=0, i;
printf("\nEnter the number of elements ");
if (1 != scanf("%d",&n))
return 1; // bad entry
if (1 > n || NUMBERS < n)
return 1; // number out of range
printf("\nEnter %d elements ", n);
for(i=0; i<n; i++){
if (1 != scanf("%d", &a[i]))
return 1; // illegal number
}
printf("\nElements are \n");
for(i=0; i<n; i++){
printf("%d ", a[i]);
}
printf("\nEnter the key ");
if (1 != scanf("%d", &x))
return 1; // bad entry
for(i=0; i<n; i++){ // <--- every element
if (x == a[i]) // <--- find matching key
count++; // <--- keep a tally
}
printf("\nThe count is %d\n", count); // (corrected) result
return 0;
}