用循环和递归实现二分查找

#include <iostream>

#define len 2

int bisectionSearch(int *a, const int &left, const int &right, const int &target)
{
if (left > right)
return -1;

int mid = (left + right) / 2;

if (a[mid] < target)
return bisectionSearch(a, mid+1, right, target);
else if (a[mid] > target)
return bisectionSearch(a, left, mid-1, target);
else
return mid;
}

int loopSearch(int *a, const int &length, const int &target)
{
int right = length - 1;
int left = 0;

int mid;

while (left <= right)
{
mid = (left + right) / 2;

if (target < a[mid])
right = mid - 1;
else if (target > a[mid])
left = mid + 1;
else
return mid;
}

return -1;
}

int main()
{
int a[len];
int right = len - 1;
int left = 0;

for (int i = 0; i < len; ++i)
std::cin >> a[i];

int x;
std::cin >> x;

int index;

index = loopSearch(a, len, x);
//index = bisectionSearch(a, left, right, x);

if (-1 != index)
std::cout << index << std::endl;
else
std::cout << "no element matches" << std::endl;

return 0;
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客