```
//Binary search
//Programming by : Erfan Nasoori
//Mail : ketn68@yahoo.com
Date of send : 2009/2/1
#include <iostream>
#include <conio>
int binarysearch(int[],int,int);
int main()
{
int sortedArray[100];
int key,n,hold,F,L,k,G,i;
cout<<"How many :";
cin>>n;
cout<<"Enter numbers :\n";
for(int i=0;i<n;++i)
{
cout<<"number["<<(i+1)<<"] = ";
cin>>sortedArray[i];
}
for(int l=1;l<=n-1;++l)
for(int j=0;j<(n-l);++j)
if(sortedArray[j]>sortedArray[j+1])
{
hold=sortedArray[j];
sortedArray[j]=sortedArray[j+1];
sortedArray[j+1]=hold;
}
cout<<"sorted numbers:";
for( i=0;i<n;++i)
cout<<sortedArray[i]<<'\t';
cout<<"\nkey:";
cin>>key;
G=binarysearch(sortedArray,n,key);
if(G == -1)
cout<<"It didn't found!";
else
cout<<"\nIts index = "<<G<<endl;
getch();
return 0;
} //end of main
//////////////////////////////////////////////////////////
int binarysearch(int sortedArray[], int n, int key)
{
int first=0,last=n-1;
while (first <= last)
{
int mid = (first + last) / 2;
if (key > sortedArray[mid])
first = mid + 1;
else if (key < sortedArray[mid])
last = mid - 1;
else
return mid;
}
return -1;
}
```

Recommended Topics