任务:分别用递归和循环两种方式实现二分查找算法(在某有序数组中查找特定的数字并返回其在数组中的下标)
代码如下:
#include <iostream>
#define NUM 20
using namespace std;
void Print(int* a, int len); // 显示当前数组
void BinarySearch_Recursion(int* a, int left,int right,int value); // 二分查找(递归实现)
void BinarySearch_Loop(int* a, int left, int right, int value); // 二分查找(循环实现)
int main()
{
int a[NUM];
for (int i = 0; i < NUM; i++)
{
a[i] = 3 * i + 1;
}
cout << "数组a: ";
Print(a, NUM);
BinarySearch_Recursion(a, 0, NUM, 55);
BinarySearch_Loop(a, 0, NUM, 31);
while (1);
return 0;
}
// 显示当前数组
void Print(int* a, int len)
{
for (int i = 0; i < len; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
// 二分查找(递归实现)
// a:被查找数组 left,right:二分查找的下标范围 value:查找的数值
void BinarySearch_Recursion(int* a, int left, int right, int value)
{
// 查找合理性检查:left应该小于right
if (left > right)
{
cout << "ERROR!"<< endl;
return;
}
// 当left==right时,直接比较当前下标是否符合要求
if (left == right)
{
if (a[left] == value)
{
cout << ">>> value: " << value << " index: " << left << endl;
return;
}
else
{
cout << ">>> No such value: " << value << endl;
return;
}
}
//递归:取下标范围中间处的值,若等于value,则输出结果,否则更改下标范围继续递归
int mid = (left + right) / 2;
if (a[mid] == value)
{
cout << ">>> value: " << value << " index: " << mid << endl;
return;
}
if (a[mid] > value)
{
BinarySearch_Recursion(a, left, mid, value);
}
else
{
BinarySearch_Recursion(a, mid+1, right, value);
}
}
// 二分查找(循环实现)
// a:被查找数组 left,right:二分查找的下标范围 value:查找的数值
void BinarySearch_Loop(int* a, int left, int right, int value)
{
// 查找合理性检查:left应该小于right
if (left > right)
{
cout << "ERROR!" << endl;
return;
}
// 当left==right时,直接比较当前下标是否符合要求
if (left == right)
{
if (a[left] == value)
{
cout << ">>> value: " << value << " index: " << left << endl;
return;
}
else
{
cout << ">>> No such value: " << value << endl;
return;
}
}
//循环:取下标范围中间处的值,若等于value,则跳出循环输出结果,否则更改下标范围继续循环
int mid = (left + right) / 2;
while (a[mid] != value && left!=right)
{
mid = (left + right) / 2;
if (a[mid] > value)
{
right = mid;
}
else
{
left = mid+1;
}
mid = (left + right) / 2;
}
if (a[mid] == value)
{
cout << ">>> value: " << value << " index: " << mid << endl;
return;
}
else
{
cout << ">>> No such value: " << value << endl;
return;
}
}