1010: 折半查找的实现

解法:

cpp 复制代码
#include<iostream>
#include<vector>
using namespace std;
void solve() {
	int n;
	cin >> n;
	vector<int> vec(n);
	for (int& x : vec) cin >> x;
	int x;
	cin >> x;
	int l = 0, r = n-1, cnt = 0;
	while (l <= r) {
		cnt++;
		int mid = l + (r - l) / 2;
		if (vec[mid] > x) 
			r = mid - 1;
		else if (vec[mid] < x)
			l = mid + 1;
		else {
			cout << mid << endl;
			cout << cnt;
			return;
		}
	}
	cout << -1 << endl;
	cout << cnt;
}
int main() {
	solve();
	return 0;
}
相关推荐
小糖学代码19 小时前
Linux:11.线程概念与控制
linux·服务器·c语言·开发语言·c++
科研小白_20 小时前
基于遗传算法优化BP神经网络(GA-BP)的数据时序预测
人工智能·算法·回归
Terry Cao 漕河泾20 小时前
基于dtw算法的动作、动态识别
算法
Larry_Yanan1 天前
QML学习笔记(四十)QML的ApplicationWindow和StackView
c++·笔记·qt·学习·ui
Miraitowa_cheems1 天前
LeetCode算法日记 - Day 73: 最小路径和、地下城游戏
数据结构·算法·leetcode·职场和发展·深度优先·动态规划·推荐算法
野蛮人6号1 天前
力扣热题100道之560和位K的子数组
数据结构·算法·leetcode
Swift社区1 天前
LeetCode 400 - 第 N 位数字
算法·leetcode·职场和发展
fengfuyao9851 天前
BCH码编译码仿真与误码率性能分析
算法
Kratzdisteln1 天前
【C语言】Dev-C++如何编译C语言程序?从安装到运行一步到位
c语言·c++
小白不想白a1 天前
每日手撕算法--哈希映射/链表存储数求和
数据结构·算法