1010: 折半查找的实现

解法:

#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;
}

相关推荐

  1. 查找——顺序查找折半查找

    2024-05-10 00:12:04       33 阅读
  2. 折半查找(数据结构实训)

    2024-05-10 00:12:04       65 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-10 00:12:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-10 00:12:04       101 阅读
  3. 在Django里面运行非项目文件

    2024-05-10 00:12:04       82 阅读
  4. Python语言-面向对象

    2024-05-10 00:12:04       91 阅读

热门阅读

  1. Scala基础学习-循环

    2024-05-10 00:12:04       31 阅读
  2. redis之集群

    2024-05-10 00:12:04       25 阅读
  3. 【QEMU系统分析之实例篇(十八)】

    2024-05-10 00:12:04       29 阅读
  4. vue 钩子函数updated什么时候触发

    2024-05-10 00:12:04       33 阅读
  5. 获取xml内容,使用dom4J

    2024-05-10 00:12:04       34 阅读
  6. 秋招后端开发面试题 - JVM类加载机制

    2024-05-10 00:12:04       28 阅读