算法思想
折半查找:又称二分查找,适用于有序的顺序表。
先将中间位置元素与Key进行比较
若相等,则返回中间位置下标
若不相等:
① key<中间值,在左半边继续查找
② key>中间值,在右半边继续查找
算法实现
int BinarySearch(sqList L,int key)
{
int low=0,high=L.length-1;
while(low<=high)//'<='很关键
{
int mid=(low+high)/2;
if(L.data[mid]==key)
return mid+1;
else if(key<L.data[mid])
high=mid-1;
else
low=mid+1;
}
return -1;
}
运行代码
#include "stdafx.h"
#include<iostream>
using namespace std;
#define MaxSize 50
typedef struct
{
int data[MaxSize];
int length;
}sqList;
void Creat(sqList &L);
int Search(sqList L,int key);//顺序查找
int Binary_Search(sqList L,int key);//二分查找
int _tmain(int argc, _TCHAR* argv[])
{
sqList l;int x;
Creat(l);
cout<<"2在第"<<Binary_Search(l,2)<<"个位置。"<<endl;
cout<<"5在第"<<Binary_Search(l,5)<<"个位置。"<<endl;
system("pause");
return 0;
}
void Creat(sqList &L)
{
for(int i=0;i<5;i++)
{
L.data[i]=i+1;
}
L.length =5;
for (int i = 0; i < L.length; i++)
{
cout<<L.data[i]<<" ";
}
cout<<endl<<endl;
}
int Search(sqList L,int key)
{
for (int i = 0; i < L.length; i++)
{
if(L.data[i]==key)
return i+1;
}
return -1;
}
int Binary_Search(sqList L,int key)
{
int low=0,high=L.length-1;
while(low<=high)//‘<=’很关键
{
int mid=(low+high)/2;
if(L.data[mid]==key)
return mid+1;
else if(key<L.data[mid])
high=mid-1;
else
low=mid+1;
}
return -1;
}
运行结果
来源:CSDN
作者:Demon、
链接:https://blog.csdn.net/weixin_43656327/article/details/104755545