Binary Search
Binary Search
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int list[100];
int i,j,n,pos,x;
int first,middle,last,temp,ci,cc;
ci=cc=0;
clrscr();
cout<<"\nEnter the size of list: ";
cin>>n;
cout<<"\nEnter the Elements of the Array\n";
for(i=0;i<n;i++)
cin>>list[i];
first=0;
pos=-1;
last=n-1;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(list[j]>list[j+1])
{
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
}
}
}
clrscr();
cout<<"\nNo.s entered are:\n";
for(i=0;i<n;i++)
cout<<list[i]<<" ";
cout<<"\n\n\nEnter the Value to be searched: ";
cin>>x;
while((first<=last)&&(pos==-1))
{
ci++;
middle=(first+last)/2;
cc++;
if(list[middle]==x)
{
pos=middle;
}
else
{
cc++;
if(list[middle]<x)
{
first=middle+1;
}
else
{
last=middle-1;
}
}
}
if(pos>-1)
{
cout<<"\n\nElement found at position:"<<++pos;
cout<<"\nInteration counter:"<<ci;
cout<<"\nComparison counter:"<<cc;
}
else
cout<<"\n\nSearch Unsuccessfull!!";
getch();
}
OUTPUT
Successful Search
Enter the size of list: 5
Enter the Elements of the Array
22
54
23
12
10
No.s entered are:
10 12 22 23 54
Enter the Value to be searched: 22
Element found at position:3
Interation counter:1
Comparison counter:1
Unsuccessful Search
Enter the size of list: 5
Enter the Elements of the Array
23
11
67
323
5
No.s entered are:
5 11 23 67 323
Enter the Value to be searched:10
Search Unsuccessfull!!
Interation counter:3
Comparison counter:6