C++ 二分查找算法的代码

在代码期间,将开发过程中常用的代码段做个收藏,如下的代码是关于C++ 二分查找算法的代码,希望对各位朋友也有用处。
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;
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;
}




 

posted @ 2019-07-26 11:55  C_Cricket  阅读(1004)  评论(0编辑  收藏  举报