Tuesday, May 1, 2012

Design an efficient algorithm that finds the index of first occurance of an element larger than a specified key k; return -1 if every element is less than or equal to k.

This can also be solved by doing little modification in binary search program. Below is the fully working code in C.

#include<stdio.h>
int bsearch(int a[],int size,int elem)
{
    int low=0;
    int up=size-1;
    int mid;
    while(low <= up) {
        mid=(low+up)/2;
        if(a[mid]==elem)
        {        if(mid+1 <= up)
                    if(a[mid+1]>elem)
                        return mid+1;
                    else
                        low = mid+1;
                else
                    return -1;
        }
        else if(a[mid]<elem)
        {
            low = mid + 1;
            if(a[low]>elem)
                return low;
        }
        else
        {
            up = mid -1;
            if(a[up]<=elem)
                return up+1;
        }
    }
    return -1;
}
int main()
{
    int arr[10]={1,2,3,3,4,6,9,9,9,10};
    int pos,srch_elem;
    printf("Enter element to search : ");
    scanf("%d",&srch_elem);
    pos=bsearch(arr,10,srch_elem);
    if(pos == -1)
        printf("element greater than %d is not in array\n",srch_elem);
    else
        printf("first element greater than %d is %d at location %d\n",srch_elem,arr[pos],pos+1);
    return 0;
}

No comments:

Post a Comment