首页 > 代码库 > C++实现二分检索算法

C++实现二分检索算法

C++实现二分检索算法
#include <iostream>
#include <iomanip>
#include<stdlib.h>
using namespace std;
void enter(int arrayin[], int n); //输入函数
void asort(int arrayin[], int n); //排序函数
int Search(int number,int arraylength,int array[]); //查找函数
const int N=10;
int main()
{
int array[N]={0};
enter(array,N); //调用输入函数
asort(array,N); //调用排序函数
cout<<"The array have been sorted as shown below:"<<endl;
for(int i=0;i<N;i++)
{
cout<<" "<<array[i]; //打印已经排好序的数组
}
cout<<"\n";
int number=0;
cout<<"please enter the number that you want to search:"<<endl;
cin>>number;
number=Search(number,N,array); //调用查找函数
if(number==-1)
{
cout<<"The number you entered is not in the array!"<<endl;
}
else
{
cout<<"你要查找的数是第"<<number+1<<"个数,其值为:
"<<array[number]<<endl; //输出结果
}
system("pause");
return 0;
}
//输入函数
void enter(int arrayin[], int n)
{
cout<<"please enter "<<N<<" numbers:"<<endl;
for(int i=0;i<n;i++){
cin>>arrayin[i]; //输入 10 个数到数组中
}
}
//排序函数
void asort(int arrayin[], int n)
{
int temp=0,i;
for ( i=0;i<n-1;i++) //冒泡排序
{
for (int j=i+1;j<n;j++)
{
if (arrayin[i]> arrayin[j])
{
temp=arrayin[i];
arrayin[i]=arrayin[j];
arrayin[j]=temp;
}
}
}
}
//查找函数
int Search(int number,int arraylength,int arrayin[])
{
int First=0,Last=arraylength-1, Middle=(First+Last)/2;
while(First<=Last)
{
if(number<arrayin[First] || number>arrayin[Last] ) {return -1;}
if(number==arrayin[Middle]) {return Middle;}
if(number>arrayin[Middle]) {First=(Middle+1);}
else {Last=(Middle-1);}
Middle=(First+Last)/2;
}
}

详细文档参见  http://files.cnblogs.com/Goergia/C%E5%8A%A0%E5%8A%A0%E5%AE%9E%E7%8E%B0%E4%BA%8C%E5%88%86%E6%A3%80%E7%B4%A2%E7%AE%97%E6%B3%95.pdf

C++实现二分检索算法