折半查找的前提是在有序序列里查找。
#include<iostream>
using namespace std;
int BinarySearch(int a[], int size,int x)
{
int left = 0, right = size-1;
while (left <= right)
{
int mid =(left + right) / 2;
if (a[mid] == x)
return mid;
else if (a[mid] > x)
right = mid - 1;
else left = mid + 1;
}
return -1;
}
int main()
{
int arr[10] = { 1,5,14,18,20,21,45,80,81,100};
int x;
cout << "输入要查询的数:";
cin >> x;
int result=BinarySearch(arr,10, x);
if (result == -1)
{
cout << "该元素未找到" << endl;
}
else cout << "该元素存在且索引为"<<result << endl;
return 0;
}
标签:折半,right,int,mid,BinarySearch,查找,left
From: https://blog.csdn.net/weixin_73598089/article/details/140465164