二分查找的前提条件是:查找的对象必须是有序的数组。然后用中间位置的元素与要查找的值进行比较,不断的来缩小查找的范围。
一、递归方法
- 当数组为空时,返回false
- 递归的终止条件是起始索引大于终止索引
- 求中间位置的元素下标用 mid = startIndex + (endIndex - startIndex) / 2 ,而不是 mid = (startIndex + endIndex ) / 2 ,可以防止下标溢出
- 递归时的搜索范围在 [ startIndex, mid-1 ] 或 [ mid + 1, endIndex ] 之间
#include<iostream>
using namespace std;
bool BinarySearch(int arr[],int number,int startIndex,int endIndex)
{
if (arr == nullptr || startIndex > endIndex)
{
cout << "Not find the key number in the arr" << endl;
return false;
}
// 中间位置元素的下标
int mid = startIndex + (endIndex - startIndex) / 2;
if (arr[mid] == number)
{
cout << "Find the key number index is " << mid << endl;
return true;
}
if (arr[mid] > number)
{
BinarySearch(arr, number, startIndex, mid-1);
}
if (arr[mid] < number)
{
BinarySearch(arr, number, mid + 1, endIndex);
}
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,88 };
int len = sizeof(arr) / sizeof(arr[0]), findNum = 4;
BinarySearch(arr, findNum, 0, len - 1);
cin.get();
}
运行结果如下:
二、非递归方法
采用循环来进行解决
#include<iostream>
using namespace std;
bool BinarySearch(int arr[],int number,int startIndex,int endIndex)
{
if (arr == nullptr || startIndex > endIndex)
{
cout << "Please check if the parameters are legal." << endl;
return false;
}
while (startIndex<=endIndex)
{
int mid = startIndex + (endIndex - startIndex) / 2;
if (arr[mid] == number)
{
cout << "The key number index is " << mid << endl;
cout << "The find number is " << arr[mid] << endl;
return true;
}
else if (arr[mid] < number)
{
startIndex = mid + 1;
}
else
{
endIndex = mid - 1;
}
}
cout << "Not find the key number in the arr" << endl;
return false;
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,88 };
int len = sizeof(arr) / sizeof(arr[0]), findNum = 4;
BinarySearch(arr, findNum, 0, len - 1);
cin.get();
}
运行结果如下: