MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / binary_search1

Function binary_search1

publication/code/chapter06/binary_search.rs:3–25  ·  view source on GitHub ↗
(nums: &[i32], num: i32)

Source from the content-addressed store, hash-verified

1// binary_search.rs
2
3fn binary_search1(nums: &[i32], num: i32) -> bool {
4 let mut low = 0;
5 let mut high = nums.len() - 1;
6 let mut found = false;
7
8 // 注意是 <= 不是 <
9 while low <= high && !found {
10 let mid: usize = (low + high) >> 1;
11
12 // 若 low + high 可能溢出,可转换为减法
13 // let mid: usize = low + ((high - low) >> 1);
14
15 if num == nums[mid] {
16 found = true;
17 } else if num < nums[mid] {
18 high = mid - 1; // num < 中间值,省去后半部数据
19 } else {
20 low = mid + 1; // num >= 中间值,省去前半部数据
21 }
22 }
23
24 found
25}
26
27fn binary_search2(nums: &[i32], num: i32) -> bool {
28 // 基本情况1: 项不存在

Callers 1

mainFunction · 0.70

Calls 1

lenMethod · 0.45

Tested by

no test coverage detected