二分查找的递归和非递归实现
#include <iostream>
using namespace std;
//非递归
int BinarySearch(int arr[], int size, int k)
{
int left = 0, right = size - 1;
int mid;
while (left <= right)
{
mid = (left + right) / 2;
if (arr[mid] == k)
return mid;
else if (arr[mid] > k)
right = mid - 1;
else
left = mid + 1;
}
return -1;
}
//递归
int BinarySearchR(int arr[],int left,int right, int k)
{
if (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] == k)
return mid;
else if (arr[mid] > k)
return BinarySearchR(arr, left, mid - 1, k);
else
return BinarySearchR(arr, mid + 1, right, k);
}
else
return -1;
}