折半查找
程序员文章站
2024-03-20 18:50:34
...
/**********
*Author:Pug_
*Time:2019-2-26 22:23:57
*Version:1.0
*FUnction:使用折半查找在数列中查找指定数
***********/
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#define random(x,y) (rand()%(y-x)+x)
#define length(array) sizeof(array)/sizeof(array[0])
using namespace std;
int main(){
srand((int)time(0));//随机数种子
int searchNumber;
int Arr[100] ;
Arr[0] = 1;
//数组初始化赋值
cout<<setw(5)<<left<<Arr[0];
for (int i = 1;i<length(Arr);i++){
Arr[i] = Arr[i-1]+random(1,5);
cout<<setw(5)<<left<<Arr[i];
}
cout<<endl
<<"请输入需要查找的数(搜索范围为"<<Arr[0]<<"~"<<Arr[length(Arr)-1]<<"):";
cin>> searchNumber;
int left = 0;//左指针
int right = length(Arr)-1;//右指针
int mid = (right +left)/2;//中间指针
int count = 0;//计数器
while(left<=right)//注意循环的条件
{
count++;
mid = (right +left)/2;//重新指定新的中间指针
if(Arr[mid] == searchNumber)//查找到要搜索的数
{
cout<<endl<<"此数所在位置为Arr["<<mid<<"]"<<endl<<endl;
break;
}
else
if(Arr[mid]<searchNumber) //搜索范围向右缩小
{
left = mid + 1;
}
else//搜索范围向左缩小
{
right = mid - 1;
}
}
if(left>right) cout<<endl<<"未找到!" <<endl<<endl;
cout<<"总查找次数:"<<count;
return 0;
}
折半查找使用二分查找算法,其时间复杂度为 O(log2n) !!!