二分搜索
给定一组有序的数组,查找特定数字的位置(下标),
代码
本题目分为升序搜索和降序搜索,代码如下
#include<iostream>
using namespace std;
int a[100];
//升序时的搜索
int BSearch_ascending(int low, int high, int x)
{
int mid;
if (low > high)
return -1;
else
{
mid = (high + low) / 2;
if (x == a[mid])
return mid;
else if (a[mid] < x)
return BSearch_ascending(mid + 1, high, x);
else
return BSearch_ascending(low, mid - 1, x);
}
}
//降序时的搜索
int BSearch_descending(int low, int high, int x)
{
int mid;
if (low > high)
return -1;
else
{
mid = (high + low) / 2;
if (x == a[mid])
return mid;
else if (a[mid] > x)
return BSearch_descending(mid + 1, high, x);
else
return BSearch_descending(low, mid - 1, x);
}
}
int main()
{
int n, x, i, m, order;
cin >> n >> m >> order;
for (i = 0; i < n; ++i)
cin >> a[i];
//order为1时升序搜索
if (order == 1)
{
if (BSearch_ascending(0, n, m) >= 0)
cout << BSearch_ascending(0, n, m);
else
cout << "Not found\n" << endl;
}
//order为0时降序搜索
else if (order == 0)
{
if (BSearch_descending(0, n, m) >= 0)
cout << BSearch_descending(0, n, m);
else
cout << "Not found\n" << endl;
}
return 0;
}