Friday, March 23, 2012

Find number of occurances of a number

 Given a sorted array with duplicate elements, find the number of occurrences of x.

http://www.geeksforgeeks.org/count-number-of-occurrences-in-a-sorted-array/

Strategy:
We will use the modified binary search to solve this in O(log n) time. Here is the code,

Code:
#include <stdio.h>
#include <stdlib.h>

int count(int* arr, int x, int start, int end)
{
    if(start > end)
        return 0;

    int mid = (start+end)/2;
    int cnt = 0;

    if(arr[mid] == x)
        cnt = 1 + count(arr, x, start, mid-1) + count(arr, x, mid+1, end);
    else if(arr[mid] > x)
        cnt = count(arr, x, start, mid-1);
    else
        cnt = count(arr, x, mid+1, end);

    return cnt;
}

int main()
{
    int arr[]={1,2,3,3,3,3,3,4};
    int len=sizeof(arr)/sizeof(arr[0]);

    printf("Total count = %d\n", count(arr, 3, 0, len-1));

    return 0;
}

No comments:

Post a Comment