c - 排序数组中元素出现的次数

标签 c binary-search

我想找出一个元素在排序数组中出现的次数。我使用 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/

相关文章:

algorithm - 比较顺序搜索和二分搜索

search - 二分搜索 - 最坏/平均情况

ruby - Ruby 中是否有内置的二进制搜索?

java - 追加 ArrayList.remove 和 ArrayList.set 时出错

c# - 在 C# 中使用列表进行二进制搜索

c - 按升序插入单链表

c - 如何在printf中连接数字

c - 按负计数右移不仅未定义,而且在 clang 中映射为一对多

c++ - 为什么这段代码中的 while 循环会在 0 处停止?

c - 读取(C 函数)行为异常