折半法的简单应用

#include <iostream>
using namespace std;
int main()
{
int number;
cout<<"please input the length of array"<<endl;
cin>>number;
int *a=new int[number];
for (int i=0;i<number;i++)
{
cout<<endl;
printf("please input the %d element \n",i+1 );
cin>>a[i];
}
cout<<"please input the objective number"<<endl;
int number2;
cin>>number2;
int count=1;
int begin=0;
int end=number-1;
int start;
int index;
while (count<=number)
{
start=(begin+end)/2;
if (number2==a[start])
{
index=start+1;
break;
}
else if (number2>a[start])
{
begin=start+1;
start=(begin+end)/2;
count++;
}
else if (number2<a[start])
{
begin=0;
end=start-1;
start=(begin+end)/2;
count++;
}
}
if (count  > number)
cout<<"there don't exist the objective number in the array"<<endl;
else if (count<=number)
{
cout<<"the wanted number's index is ";
cout<<index<<endl;
}
return 0;
}

你可能感兴趣的:(折半法的简单应用)