时间限制:1000MS 代码长度限制:10KB
提交次数:4655 通过次数:1446
题型: 编程题 语言: G++;GCC
Description
编写Search_Bin函数,实现在一个递增有序数组ST中采用折半查找法确定元素位置的算法.
输入格式
第一行:元素个数n 第二行:依次输入n个元素的值(有序) 第三行:输入要查找的关键字key的值
输出格式
输出分两种情形: 1.如果key值存在,则输出其在表中的位置x(表位置从0开始),格式为The element position is x. 2.如果key值不存在输出:"The element is not exist."
输入样例
6 1 3 5 7 9 10 5
输出样例
The element position is 2.
作者
yqm
Version:
0
#include <iostream>
using namespace std;
int binaryFind(int* ans, int key)
{
int low = 1, high = ans[0];
int mid = (low+high) / 2;
while (low <= high) {
mid = (low + high) / 2;
if (ans[mid] == key)
return mid;
else if (ans[mid] > key)
high = mid - 1;
else
low = mid + 1;
}
return 0;
}
int main()
{
int i, n, key, t;
int ans[1000];
cin >> n;
ans[0] = n;
for (i = 1; i <= n; i++)
cin >> ans[i];
cin >> key;
t = binaryFind(ans, key);
if(t)
cout << "The element position is " << t-1 << ".";
else
cout << "The element is not exist.";
}