Binary Search

#include<stdio.h>

int binary(int a[],int i,int j,int v)
{
    int mid;
    if(j<i)
        return -1;
    mid=(i+j)/2;
    if(a[mid]>v)
        return binary(a,i,mid-1,v);
    else if(a[mid]<v)
        return binary(a,mid+1,j,v);
    else
        return mid;
}

void main()
{
    int a[100],n,v,i,t;
    printf("Enter no. elements ");
    scanf("%d",&n);
    printf("Enter elements ");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("Enter the number to be searched ") ;
    scanf("%d",&v);
    t=binary(a,0,n-1,v);
    if(t==-1)
        printf("Number not found");
    else
        printf("Number found at position %d",t+1);
}

/*Output
Enter no. elements 5
Enter elements 65 98 44 112 36
Enter the number to be searched 112
Number found at position 4
*/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s