1.递归算法
#include<iostream>
using namespace std;
int zheban(int arr[], int low, int length, int x)
{
if (low > length)
{
return -1;
}
int mid = (low + length) / 2;
if (x == arr[mid])
{
return mid;
}
else if (x > arr[mid])
{
return zheban(arr, mid + 1, length, x);
}
else if (x < arr[mid])
{
return zheban(arr, low, mid - 1, x);
}
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int a;
cout << "请输入要寻找的数值: ";
cin >> a;
int low = 0;
int length = sizeof(arr) / sizeof(arr[0]) ;
int score = zheban(arr, low, length, a);
if (score == -1)
{
cout << "在数组中找不到这个数" << endl;
}
else
{
cout << "这个数的位置为" << score+1 << endl;
}
return 0;
}
折半查找的非递归算法
#include<iostream>
#include<algorithm>
using namespace std;
void zheban(int arr[],int length,int a)
{
int low = 0;
int height =length-1;
int mid;
while (low <=height)
{
mid = low+(height-low)/ 2;
if (a < arr[mid])
{
height = mid - 1;
}
else if (a > arr[mid])
{
low = mid + 1;
}
else
{
cout << "找到了位置在" << mid + 1;
break;
}
}
if (low > height)
{
cout <<"找不到这个数的位置";
}
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int a;
cout <<"请输入要寻找的数值";
cin >> a;
int length= sizeof(arr) / sizeof(arr[0]);
zheban(arr,length,a);
return 0;
}