8621 二分查找

时间限制: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.

#include<iostream>
#include<cstdio>
using namespace std;

int Search_Bin(int A[],int x, int y,int a)
{
	int m;
	while (y > x){
		m = x + (y - x) / 2;
		if (A[m] == a) {
			return m+1;
		}
		else if (A[m] > a) {
			y = m;
		}
		else
			x = m + 1;
	}
	return 0;
}

int main()
{
	int n;
	cin >> n;
	int *a;
	a = new int[n];
	for (int i = 0; i < n; i++){
		cin >> a[i];
	}
	int aim,pos;
	cin >> aim;
	if (Search_Bin(a, 0, n, aim)) {
		pos = Search_Bin(a, 0, n, aim);
		printf("The element position is %d.", pos-1);
	}
	else
		cout << "The element is not exist.";
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值