Tuesday, February 17, 2015

Binary search implementation using C language

#include<stdio.h>
#include<conio.h>
#define MAX 20

int bsearch(int [],int,int,int);

void main()
{
int a[10],i,t,f=0,n,l,k;
int bsearch(int[],int,int,int);
clrscr();
printf("\n\nEnter the size of an array: ");
scanf("%d",&n);

if (n>MAX)
{
printf("\nInvalid Index\n");
}
else
{
printf("\nEnter the array elements:\n");
}

    for(i=0;i<n;i++)
    {
    scanf("%d",&a[i]);
    }

printf("\n\n Enter element for search: ");
scanf("%d",&t);
l=n-1;
k=bsearch(a,f,l,t);

    if(k==-1)
    {
    printf("\n Element is not found\n");
    }
    else
    {
    printf("\n\nElement is found at location: %d",k);
    }

getch();
}

int bsearch(int list[],int f,int l,int t)//Binary Search function implementation
{
int m;
    while(f<=l)
    {
    m=(f+l)/2;
       
        if(list[m]==t)
        {
        return m;
        }
            else if(t<list[m])
            {
            l=m-1;
            }
                else if(t>list[m])
                {
                f=m+1;
                }
    }
return(1);
}


No comments: