二分查找
作为查找算法中最基础的查找算法,时间复杂度为O(logn)。前提是序列有序,每次取序列中位数跟关键字比较,相等则返回中位数所在位置索引;小于关键字,则在中位数位置之后的子序列中继续取子序列中位数同关键字比较;大于关键字,则在中位数位置之前的子序列中继续取该子序列的中位数同关键字比较。
二分查找C++实现代码如下:
// 二分查找
#include <iostream>
using namespace std;
int BinarySearch(int *input, int goal, int len)
{
if (input == nullptr || len <= 0) return -1;
int low = 0;
int high = len - 1;
while (low <= high)
{
int middle = (high - low) / 2 + low;
if (input[middle] == goal)
{
return middle;
}
else if (input[middle] > goal)
{
high = middle - 1;
}
else
{
low = middle + 1;
}
}
return -1;
}
int main(int argc, char *argv[])
{
int input[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int goal = 6;
if (BinarySearch(input,goal,9) != -1)
{
cout << goal << "在数组中位置是:" << BinarySearch(input, goal, 9) << endl;
}
else
{
cout << goal + "不在数组中" << endl;
}
system("pause");
return 0;
}