需要在在长度为n的数组中,查找target,并且输出其在数组中的下标。
(前置条件:数组已排序)
若数组未排序,则可以放入容器中(如:vector),进行sort
(前置条件:数组已排序)
若数组未排序,则可以放入容器中(如:vector),进行sort
#include<iostream>
using namespace std;
static int index = 0;
static int mid;
void binarySearch(int a[],int len,int target,bool &found)
{
int start = 0, last = len -1;
while ( (start < last) && !found)
{
mid = (start+last+1)/2;
if (target < a[mid])
last = mid -1;
else if (target > a[mid])
start = mid + 1;
else
found = true;
}
index = mid;
}
int main()
{
int target;
cin >> target;
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
bool found = false;
binarySearch(arr,n,target,found);
cout << found << " " << index << " " << arr[index];
return 0;
}