Wednesday 26 October 2011

Implementation of binary search algorithm

/*
ALGORITHM:
1.  low = 1,high = n
2.  Repeat step 3 to 5 while low <= high
3.  mid = (low + high)/2
4.  If a[mid] = x
            Print “ found at mid”
            Return
5.  If (a[mid] < x)
                        low = mid + 1
            Else
                        High = mid – 1
6.  Print “x not found”
7.  Exit
*/
//Program implemented by shadab khan
#include <stdio.h>
#include <conio.h>
Void main()
{
Int a[100],i,loc,mid,beg,end,n,flag=0,item;
clrscr();
printf("How many elements");
scanf("%d",&n);
printf("Enter the element of the array\n");
for(i=0;i<=n-1;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to be searching\n");
scanf("%d",&item);
loc=0;
beg=0;
end=n-1;
while((beg<=end)&&(item!=a[mid]))
{
mid=((beg+end)/2);
if(item==a[mid])
{
printf("search is successfull\n");
loc=mid;
printf("position of the item%d\n",loc+1);
flag=flag+1;
}
if(item<a[mid])
end=mid-1;
else
beg=mid+1;
}
if(flag==0)
{
printf("search is not successfull\n");
}
getch();
}

No comments:

Post a Comment