#include <iostream>
#include <vector>
#include <stack>
#include <cstring>
#include <string>
#include <queue>
#include <algorithm>
#include "TreeNode.h"
#include "ListNode.h"
using namespace std;
// 二分查找具有O(logn)的时间复杂度,很强,但是只能用于数组的数据结构,像链表就不适合
// 二分查找非递归法
int binarySearch(int num[], int length, int key){
if(length < 1)
return -1;
int low = 0;
int high = length - 1;
int middle = 0;
while(low <= high){
// 以后尽量使用位运算,不直接用(low + high) / 2是为了防止加法溢出
middle = low + ((high - low) >> 1);
if(num[middle] == key)
return middle;
if(num[middle] > key)
high = middle - 1;
else if(num[middle] < key)
low = middle + 1;
}
// 没找到则返回-1
return -1;
}
// 二分查找递归方法
int binarySearchPlus(int num[], int low, int high, int key){
if(low > high)
return -1;
int middle = low + ((high - low) >> 1);
if(num[middle] == key)
return middle;
if(num[middle] > key)
return binarySearchPlus(num, low, middle - 1, key);
else
return binarySearchPlus(num, middle + 1, high, key);
}
int main(int argc, char* argv[]){
int arr[8] = {8,7,6,5,4,3,2,1};
cout<<binarySearch(arr, 8, 5)<<endl;
cout<<binarySearchPlus(arr, 0, 7, 5)<<endl;
return 0;
}
原文:https://www.cnblogs.com/flyingrun/p/13423302.html