Pages

Visitors

Thursday 5 January 2012

Binary Search


#include <stdio.h>

main()

{
    int a[30],n,i,t,low,mid,high,found = 0;

    printf("\n enter the number of elements in array");

    scanf("%d",&n);

    if(n>30)

    {
        printf("\n too many numbers");
        exit(0);
    }

printf("\n enter elements of array: ");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

printf("\n enter element to search: ");

scanf("%d",&t);

low = 0;

high = n-1;

while (high >= low)

{
    mid = (low+high)/2;

    if (a[mid] == t)
    {
        found = 1; break;
    }

    else if (t<a[mid])

             high = mid-1;

             else low = mid + 1;
}

if (found ==0)

printf("\n not found");

else printf("\n found at %d",mid);

getch();
}

No comments:

Post a Comment