Source Code:-
#include <iostream.h>
#include <conio.h>
void main()
{ clrscr();
int c, first, last, middle, n, search, array[100];
cout<<"Program for Binary Search by-Tarun Rawat\n";
cout<<"\nEnter number of elements : ";
cin>>n;
cout<<"Enter "<<n<<" integers \n";
for ( c = 0 ; c < n ; c++ )
cin>>array[c];
cout<<"\nEnter value to find it's location\n";
cin>>search;
first = 0;
last = n - 1;
middle = (first+last)/2;
while( first <= last )
{ if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
cout<<search<<" found at location "<< middle+1;
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
cout<<"Not found! "<<search<<" is not present in the list.\n";
getch();
}
No comments:
Post a Comment