一 代码
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
bool BinarySearch(int * array, int aSize, int key){
if (array == NULL || aSize == 0) {
return false;
}
int low = 0;
int mid = 0;
int high = aSize - 1;
while(low <= high) {
mid = (low + high) / 2;
if (key > array[mid]) {
low = mid + 1;
} else if (key < array[mid]) {
high = mid - 1;
} else {
std::cout << "exist, index = " << mid << std::endl;
return true;
}
}
std::cout << "does not exist" << std::endl;
return false;
}
int main()
{
std::cout << "hello,world" <<std::endl;
int array[5] = {1, 3, 5, 7, 9};
bool ret = BinarySearch(array, 5, 7);
std::cout << ret << std::endl;
ret = BinarySearch(array, 5, 4);
std::cout << ret << std::endl;
return 0;
}
hello,world
exist, index = 3
1
does not exist
0
请按任意键继续. . .
二 算法原理
前提:有序数组,取出最左low,最右边界high。在whilie循环中,对比查找key和居中值array[mid]的大小,即可确定key的存在范围。在范围内进行查找即可。