Implement a function of binary search and count the steps executed by function on various inputs for best case and worst case. Also write complexity in each case and draw a comparative chart.
#include<stdio.h>
#include<conio.h>
#define size
10
unsigned long
count=0;
void
binary_search(int a[],int no)
{
int low=0,high=size-1,middle;
count++;
while(low<=high)
{
count++;
middle = (low+high)/2;
count++;
if(a[middle]>no)
{
count++;
high=middle-1;
}
else if(a[middle]<no)
{
count++;
count++;
low=middle+1;
}
else
{
count++;
count++;
return;
}
}
count++;
count++;
return;
}
void main()
{
int a[size],i,no,index;
clrscr();
for(i=0;i<size;i++)
{
a[i]=i+1;
}
printf("Enter which element you want
to find : ");
scanf("%d",&no);
binary_search(a,no);
printf("Count= %lu",count);
getch();
}
Comments
Post a Comment