Tuesday, May 1, 2012

Write a program that takes a sorted array A and a key elem and returns the index of first occurance of key in A, and returns -1 if key doesnot appears in A.

Above problem can be solved by doing simple modification of binary search program. Below is the 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(a[mid-1] == elem)
                                up=mid-1;
                        else
                                return mid;
                }
                else if(a[mid]<elem)
                        low=mid+1;
                else
                        up=mid-1;
        }
        return -1;
}
int main()
{
        int arr[10]={1,3,3,3,3,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("%d is not in array\n",srch_elem);
        else
                printf("first occurance of %d is at location %d\n",srch_elem,pos+1);
        return 0;
}

No comments:

Post a Comment