关于二分查找法
二分查找法主要是解决在“一堆数中找出指定的数”这类问题。
而想要应用二分查找法,这“一堆数”必须有一下特征:
- 存储在数组中
- 有序排列
所以如果是用链表存储的,就无法在其上应用二分查找法了。(曽在面试被问二分查找法可以什么数据结构上使用:数组?链表?)
至于是顺序递增排列还是递减排列,数组中是否存在相同的元素都不要紧。不过一般情况,我们还是希望并假设数组是递增排列,数组中的元素互不相同。
以下为测试程序:
#include <iostream>
using namespace std;
//非递归实现
int BinarySearch(int array[], int len, int value)
{
if (array == NULL || len <= 0)
return -1;
int low = 0;
int high = len - 1;
while (low <= high)
{
int mid = low + (high - low) / 2;
if (array[mid] == value)
return mid;
else if (array[mid] > value)
high = mid - 1;
else
low = mid + 1;
}
return -1;
}
//递归实现
int BinarySearch_Recursive(int array[], int low, int high, int value)
{
if (low > high)
return -1;
int mid = low + (high - low) / 2;
if (array[mid] == value)
return mid;
else if (array[mid] > value)
return BinarySearch_Recursive(array, low, mid - 1, value);
else
return BinarySearch_Recursive(array, mid + 1, high, value);
}
int main(int argc, char *argv[])
{
int i, j;
int arr[10];
for (i = 0; i < 10; i++)
{
arr[i] = i * 2;
}
cout << "Input the search number:";
cin >> j;
int location = BinarySearch(arr, 10, j);
if (location != -1)
cout << "Exist1:" << location << endl;
else
cout << "Not existed in array!" << endl;
location = BinarySearch_Recursive(arr, 0, 9, j);
if (location != -1)
cout << "Exist2:" << location << endl;
else
cout << "Not existed in array!" << endl;
system("pause");
return 0;
}