/*
折半查找
说明:使用顺序表做数据结构,下标从0开始
*/
#include <iostream>
#include <cstdlib>>
using namespace std;
const int INITSIZE = 100;
typedef int ElemType;
struct SqList{
ElemType *elem;
int length;
};
//初始化顺序表
void InitList(SqList &l){
ElemType e;
int i = 0;
char c;
l.elem = (ElemType*)malloc(sizeof(ElemType)*INITSIZE);
while(cin>>l.elem[i++]){ //两个元素之间空隔分开,输入回车结束输入
c = getchar();
if(c=='\n')
break;
}
l.length = i;
}
//递归折半查找
int binarySearch1(SqList l, ElemType e, int low, int high){
if(low>high) //递归结束条件1:没有找到查找元素
return -1;
int mid = (low+high)/2;
if(l.elem[mid] == e) //递归结束条件2:找到查找元素,返回该结点下标
return mid+1;
else if(l.elem[mid] < e) //右半边
binarySearch1(l, e, mid+1, high);
else //左半边
binarySearch1(l, e, low, mid-1);
}
//非递归折半查找
int binarySearch2(SqList l, ElemType e){
int low, high, mid;
low = 0;
high = l.length-1;
while(low<=high) {
mid = (low+high)/2;
if(e == l.elem[mid])
return mid+1;
else if(l.elem[mid] < e){ //右半边
low = mid+1;
}else{ //左半边
high = mid-1;
}
}
return -1;
}
int main(){
SqList l;
ElemType x;
cout << "输入顺序表的元素(空格分隔,回车结束):" ;
InitList(l);
cout << "输入要查找的元素:";
cin >> x;
cout << "递归求取该元素的位置: " << binarySearch1(l, x, 0, l.length-1) << endl;
cout << "非递归求取该元素的位置:" << binarySearch2(l, x) << endl;
return 0;
}
程序小白,如果代码中有任何问题,欢迎指出。