Tuesday, September 24, 2013

Count number of occurences of a number in a sorted array


We will use the fact that the array is sorted. Hence we can use binary search. The only trick is that we do not stop when we find the first occurrence of the number, but continue doing the binary search to the left and right of that number.
int count(int* arr, int num, int start, int end)
{
    if(start > end)
    return 0;
    int mid = (start + end)/2;
    if(arr[mid] == num)
        return 1 + count(arr, num, start, mid-1) + count(arr, num, mid+1, end);
    else if(arr[mid] > num)
        return count(arr, num, start, mid-1);
    else
        return count(arr, num, mid+1, end);
}