// =====================【二分搜索技术 】==================
// @ author : heming
// @ date : 20170311
// @ version : 1.0
// @ description :
// =====================【二分搜索技术】==================
#include <iostream>
using namespace std;
int BinarySearch(int a[], const int x, const int n) {
int left = 0;
int right = n - 1;
int middle;
while (left <= right) {
middle = (left + right) / 2;
if (x == a[middle])
return middle;
else if (x > a[middle])
left = middle + 1;
else
right = middle - 1;
}
return -1;
}
int main()
{
int a[10];
for (int i = 0; i < 10; i++)
a[i] = i * 3;//二分搜索的前提是数组已经有序
cout << "该数组为:";
for (int i = 0; i < 10; i++)
cout<<a[i]<<" ";
cout << endl;
int x = 6;//要查找的数
int pos = BinarySearch(a, 6, 10)+1;
if (pos == -1)
cout << "search failed";
else
cout<<"要查找的数为数组的第"<<pos<<"个数"<<endl;
return 0;
}
经典算法之二分搜索技术
最新推荐文章于 2022-02-15 16:19:29 发布