折半查找(二分/对分查找)
折半查找的性能分析——判定树
与顺序查找相比:
优点:效率比顺序查找高
缺点:只适用于有序表,且仅限于顺序存储结构(对线性链表无效)
#include<iostream>
#define MAXSIZE 100
using namespace std;
typedef char KeyType;
typedef struct {
KeyType key;
}ElemType;
typedef struct {
ElemType* R;
int length;
}SSTable;
void InitST(SSTable& ST) {
ST.R = new ElemType[MAXSIZE];
ST.length = 0;//这里记录的是顺序表中元素的个数,顺序表中元素从1开始存放
}
void CreatST(SSTable& ST, int n) {
InitST(ST);
cout << "请输入线性顺序表的每个元素\n";
for (int i = 1; i <= n; i++) {
cin >> ST.R[++ST.length].key;
}
}
//输出查看线性表
void Output(SSTable ST) {
cout << "线性顺序表中的数据为\n" << "";
for (int i = 1; i <= ST.length; i++)
{
cout << ST.R[i].key << " ";
}
}
int Search_bin(SSTable ST, KeyType key) {
//初始化起点终点以及中间点
int high = ST.length;
int low = 1;
int mid = (high + low) / 2;
while (high >= low) {
if (ST.R[mid].key == key) return mid;//找到则返回
//找不到则判断下一次寻找在左半区间还是右半区间
if (ST.R[mid].key>key)//左半区间查找
{
high = mid - 1;
}
else {
low = mid + 1;
}
//重新计算中间值
mid = (high + low) / 2;
}
//循环结束说明high<low,说明找不到
return 0;
}
int helper(SSTable ST, KeyType key,int low,int high ) {
if (high < low) {
return 0;
}
int mid = (high + low) / 2;
if (ST.R[mid].key==key)
{
return mid;
}
if (ST.R[mid].key < key) {
return helper(ST, key, mid + 1, high);
}
return helper(ST, key, low, mid - 1);
}
//递归折半查找
int Search_bin_re(SSTable ST, KeyType key) {
int high = ST.length;
int low = 1;
return helper(ST, key, low, high);
}
int main() {
SSTable ST;
int n;
cout << "请输入线性顺序表的元素的个数:\n";
cin >> n;
CreatST(ST, n);
Output(ST);
KeyType key;
cout << "\n请输入需要查找的元素:\n";
cin >> key;
cout << "\n非递归查找的输出:\n";
int i=Search_bin(ST,key);
printf("%d", i);
//printf("\n%c", key);
int j = Search_bin_re(ST, key);
cout << "\n递归查找的输出:\n";
printf("%d", j);
return 0;
}