二分法递归查找数组元素

要求

 对于一个已知的升序顺序表,输入一个关键字,用二分法在数组中快速检索此关键字。

实现

 二分查找又称折半查找,可用于有序顺序表的快速关键字检索,时间效率为O(logn)。使用递归算法可以更加简洁明了的表现算法内涵。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "iostream"
#include "cstdlib"
using namespace std;

const int maxn = 7;

int BiSearch(int a[], int key, int low, int high){
if(low > high){
cout << "Not Found!" << endl;
exit(0);
}
int mid = (low+high) / 2;
if(a[mid] == key)
return mid;
else if(a[mid] < key)
BiSearch(a, key, mid+1, high);
else
BiSearch(a, key, low, mid-1);
}

int main(int argc, char const *argv[])
{
int key, a[maxn] = {1, 3, 4, 6, 9, 13, 20};
cin >> key;
cout << BiSearch(a, key, 0, maxn-1) << endl;

return 0;
}

return和exit()的区别

return退出当前函数,销毁函数的栈,返还占用的内存空间。exit()函数结束当前程序(包括主程序)。exit(x)中x取0表示程序的正常结束,取值不为0表示发生了错误,异常结束。调用exit()函数需要在头文件中包含“cstdlib”文件。


转载请注明来源:©Tinshine