二分查找
Posted AFreeMan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分查找相关的知识,希望对你有一定的参考价值。
//C语言 int binarySearch(int *arr,int len,int key) { if(arr == NULL || len <= 0) return -1; int start = 0; int end = len - 1; int mid = 0; while(start < end) { if(arr[start] == key) return start; if(arr[end] == key) return end; mid = start + (end - start) / 2; if(arr[mid] == key) return mid; else if(arr[mid] < key) start = mid+1;//必须+1,否则死循环 else end = mid-1;//必须-1,否则死循环 } return -1; }
//C++
const size_t arraySize = 10; template<typename T> int binarySearch(const array<T, arraySize> &arr, const T &key) { int mid = 0; int low = 0; int high = arraySize - 1; while (low < high) { mid = low + (high - low); if (arr[low] == key) return low; if (arr[high] == key) return high; if (arr[mid] == key) return mid; if (arr[mid] < key) low = mid + 1; else high = mid - 1; } return -1; }
时间复杂度:O(log2N)
证明:
以上是关于二分查找的主要内容,如果未能解决你的问题,请参考以下文章