/*************
二分查找的算法思想:
1.数组必须是有序的,若数组不是有序的,则需先进行排序;
2.开始默认开头位置为数组的头位置,结尾位置为数组的尾位置,中间位置为开头位置和结尾位置的折中;
A:若中间位置的数据为查找的数据,则直接返回查找成功:
B:若中间位置的数据大于查找的数据,说明查找的数据在中间位置的左边,此时改变结尾位置为中间位置的前一个位置,中间位置为原来的开头位置和新的结尾位置的折中
C:若中间位置的数据小于查找的数据,说明查找的数据在中间位置的右边,此时改变开头位置为中间位置的后一个位置,中间位置为新的开头位置和原来的结尾位置的折中
3:2操作结束后,若开头的位置大于结尾的位置,说明查找失败,数组中不存在要查找的数据
**************/
#include<iostream>
using namespace std;
#include<time.h>
#define n 10
int main()
{
int a[n]={0};
time_t ts;
srand((unsigned int)time(&ts)); //设置随机数种子
for(int i=0;i<n;i++)
{
a[i]=rand()%100; //产生随机数,并给数组赋值
cout<<a[i]<<" ";
}
cout<<endl;
//对数组进行排序:冒泡排序
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<"\n请输入查找的数据\n";
int m;
cin>>m;
//start,middle,end分别记录数组的头位置,中间位置,结尾位置
int start=0;
int end=n-1;
int middle=n/2;
while(start<=end)//查找的条件start<=end
{
if(a[middle]==m)
{
cout<<"你要查找的数据:"<<a[middle]<<endl;
break;
}
if(a[middle]>m)
{//当中间位置的数据大于查找的数据时,说明查找的数据在中间位置的左边,改变结尾位置,并重新折中查找
end=middle-1;
middle=(start+end)/2;
}
if(a[middle]<m)
{//当中间位置的数据小于查找的数据时,说明查找的数据在中间位置的右边,改变开头位置,并重新折中查找
start=middle+1;
middle=(start+end)/2;
}
}
if(start>end)//当start大于end时,说明查找的数据不存在数组
{
cout<<"error\n";
}
return 0;
}
查找算法之二分查找
最新推荐文章于 2022-02-25 18:19:43 发布