c++折半查找的次数

题目描述

给你一个无重复数的有序序列,如果采用折半查找的方式,对于给定的数,需要比较几次找到,请编程实现。

输入

第一行是N,表示序列中数的个数,序列最长1000,第二行是一个有序序列,第三行是要找的数x。

输出

如果找到x,输出折半比较的次数,否则输出NO。

样例输入

11
5 13 19 21 37 56 64 75 80 88 92
19

样例输出

2

示例代码

#include<iostream>
using namespace std;
int a[1001];

int f(int* a, int s, int e, int c, int x) {
	if (a[(e + s) / 2] == x && (e - s) != 1) {
		return c;
	}
	if ((e - s) == 1 && a[(e + s) / 2] == x || a[(e + s) / 2 + 1] == x ) {
		return c;
	}
	if (s >= e) {
		return 0;
	}
	if (a[(e + s) / 2] > x) {
		f(a, s, (e + s) / 2 - 1, c + 1, x);
	}
	else if (a[(e + s) / 2] < x) {
		f(a, (e + s) / 2 + 1, e, c + 1, x);
	}
}

int main() {
	int n;
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> a[i];
	}
	int x;
	cin >> x;
	int cnt = f(a, 1, n, 1, x);
	if (cnt == 0) {
		cout << "NO";
	}
	else {
		cout << cnt;
	}
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我已经记录下你的问题了。以下是代码实现: ```c++ #include <iostream> #include <algorithm> using namespace std; int binary_search(int arr[], int len, int target, int& count) { int left = 0, right = len - 1; while (left <= right) { count++; int mid = (left + right) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; } void descending_sort(int arr[], int len) { sort(arr, arr + len); reverse(arr, arr + len); } int main() { int arr[100], len = 0, count = 0; cout << "请输入要查找的整,以-1结束输入:" << endl; int num; cin >> num; while (num != -1) { arr[len++] = num; cin >> num; } descending_sort(arr, len); while (true) { cout << "请输入要查找的整:" << endl; int target; cin >> target; count = 0; int res = binary_search(arr, len, target, count); if (res == -1) { cout << "未找到该整!本轮查找次数:" << count << endl; } else { cout << "找到该整,位置为:" << res << ",本轮查找次数:" << count << endl; } cout << "输入1以继续查找,其他整结束查找:" << endl; cin >> num; if (num != 1) { break; } } return 0; } ``` 这段代码会先让你输入一些整,以-1结束输入,然后对这些整按降序排序,再进行折半查找。程序会循环实现多个折半查找,每轮查找都会统计查找次数,并提供继续查找的选项(输入1继续查找,其他整结束查找)。请注意,这段代码所用的查找算法只适用于已经按降序排序的组。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值