Dear all
This code shows, look for an integer number in the array of this type that we used from Binary search.
It was wrote by Borland 5.02 .
Good Luck!
//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;
}
Excuse me for 4th line.
it is a comment line.
I WRITE this sentence now.
Yesterday, I WROTE a letter to my friend.
It WAS WRITTEN with a ballpen.
We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.