针对有序数组和无序数组的对半查找。
#include <iostream>
#include <vector>
using namespace std;
// 对有序数组进行折半查找
int binary_ordered_search(vector<int> a, int target, int left, int right)
{
int mid = (left + right) / 2;
if (a[mid] == target)
return mid;
else if (a[mid] < target)
return binary_ordered_search(a, target, left, mid);
else
return binary_ordered_search(a, target, mid + 1, right);
return -1;
}
// 对无序数组进行折半查找
int binary_unordered_search(vector<int> a, int target, int left, int right)
{
int mid = (left + right) / 2;
if (a[mid] == target)
return mid;
else
{
int l = left;
int r = right;
while (l < mid)
{
if (a[l] == target)
return l;
l++;
}
return binary_unordered_search(a, target, mid, right);
}
}
int main()
{
vector<int> a = {12, 45, 2, 7, 9, 4, 7, 9, 3, 8, 0};
int target = 45;
cout << binary_unordered_search(a, target, 0, a.size() - 1) + 1 << endl;
}