对半分查找,时间复杂度O(logn)。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <string>
#include <cassert>
#include <ctime>
using namespace std;
// 二分法查找,在有序数组中查找
template<typename T>
int binarySearch(T arr[], int n, T target) {
int l = 0, r = n - 1;
while (l <= r) {
//加法有bug
int mid = l + (r - l) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] > target)
r = mid - 1;
else
l = mid + 1;
}
return -1;
}
int main() {
int n = 1000000;
int* a = new int[n];
for (int i = 0; i < n; i++)
a[i] = i;
// 测试
clock_t startTime = clock();
for (int i = 0; i < 2 * n; i++) {
int v = binarySearch(a, n, i);
if (i < n)
assert(v == i);
else
assert(v == -1);
}
clock_t endTime = clock();
cout << "时间:" << double(endTime - startTime) / CLOCKS_PER_SEC << " s" << endl;
delete[] a;
system("pause");
return 0;
}
也可以递归实现