二分查找
#include <iostream>
using namespace std;
//普通二分法
int BinarySearch_I(int* a, int n, int x);
//递归二分法
int BinarySearch_R(int* a,int x,int left,int right);
//普通二分法测试
void test01();
//递归二分法测试
void test02();
int main()
{
//test01();
test02();
return 0;
}
int BinarySearch_I(int* a, int n, int x)
{
int left = 0, right = n;
while (left < right)
{
int mid = (right + left) / 2;
if (a[mid] > x) right = mid - 1;
else if (a[mid] < x) left = mid + 1;
else return mid;
}
return -1;
}
int BinarySearch_R(int* a, int x, int left, int right)
{
if (left <= right)
{
int mid = (left + right) / 2;
if (a[mid] > x) return BinarySearch_R(a, x, left, mid - 1);
else if (a[mid < x]) return BinarySearch_R(a, x, mid + 1, right);
else return mid;
}
return -1;
}
void test01()
{
int a[] = { 1,2,3,4,5,6,7,8,9,10 };
int num = 7;
int result = BinarySearch_I(a, 10, num);
if (result < 0)
cout << "没找到!" << endl;
else
cout << "a[" << result << "} = " << num << endl;
}
void test02()
{
int a[] = { 1,2,3,4,5,6,7,8,9};
int num = 1;
int right = sizeof(a) / sizeof(int);
int result = BinarySearch_R(a,num,0,right);
if (result < 0)
cout << "没找到!" << endl;
else
cout<< "a[" << result << "} = " << num << endl;
}