折半查找
C++代码
哈工大版
/***** 折半查找 *****/
/***折半查找只适用于顺序有序表***/
#include<iostream>
using namespace std;
int binsearch1(int keyword, int list[],int low,int up) { //非递归(不推荐)
int mid;
while (low < up) {
mid = (low + up) / 2;
if (list[mid] == keyword) return mid;
else if (list[mid] > keyword) up = mid - 1;
else low = mid + 1;
}
return 0;
}
int binsearch2(int keyword, int list[], int low, int up) { //经典递归(推荐)
if (low > up) return 0;
else if (list[(low + up) / 2] > keyword) return binsearch2(keyword, list, low, (low + up) / 2 - 1);
else if (list[(low + up) / 2] < keyword) return binsearch2(keyword, list, (low + up) / 2 + 1, up);
else return (low + up) / 2;
}
int main() {
int list[10001]; //测试顺序表
for (int i = 1; i <= 10000; i++)
list[i] = i;
int adj = 0; //数组下标
int keyword = 9999;
cout << list[binsearch1(keyword, list, 1, 10000)] << endl; //测试非递归
cout << list[binsearch2(keyword, list, 1, 10000)] << endl; //测试递归
return 0;
}