mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 12:58:42 +08:00
Refactor the section of bianry search.
This commit is contained in:
@ -11,12 +11,12 @@ fn binary_search(nums: &[i32], target: i32) -> i32 {
|
||||
let mut j = nums.len() - 1;
|
||||
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
|
||||
while i <= j {
|
||||
let m = (i + j) / 2; // 计算中点索引 m
|
||||
if nums[m] < target { // 此情况说明 target 在区间 [m+1, j] 中
|
||||
let m = i + (j - i) / 2; // 计算中点索引 m
|
||||
if nums[m] < target { // 此情况说明 target 在区间 [m+1, j] 中
|
||||
i = m + 1;
|
||||
} else if nums[m] > target { // 此情况说明 target 在区间 [i, m-1] 中
|
||||
} else if nums[m] > target { // 此情况说明 target 在区间 [i, m-1] 中
|
||||
j = m - 1;
|
||||
} else { // 找到目标元素,返回其索引
|
||||
} else { // 找到目标元素,返回其索引
|
||||
return m as i32;
|
||||
}
|
||||
}
|
||||
@ -31,12 +31,12 @@ fn binary_search_lcro(nums: &[i32], target: i32) -> i32 {
|
||||
let mut j = nums.len();
|
||||
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
|
||||
while i < j {
|
||||
let m = (i + j) / 2; // 计算中点索引 m
|
||||
if nums[m] < target { // 此情况说明 target 在区间 [m+1, j) 中
|
||||
let m = i + (j - i) / 2; // 计算中点索引 m
|
||||
if nums[m] < target { // 此情况说明 target 在区间 [m+1, j) 中
|
||||
i = m + 1;
|
||||
} else if nums[m] > target { // 此情况说明 target 在区间 [i, m) 中
|
||||
} else if nums[m] > target { // 此情况说明 target 在区间 [i, m) 中
|
||||
j = m - 1;
|
||||
} else { // 找到目标元素,返回其索引
|
||||
} else { // 找到目标元素,返回其索引
|
||||
return m as i32;
|
||||
}
|
||||
}
|
||||
@ -56,4 +56,4 @@ pub fn main() {
|
||||
// 二分查找(左闭右开)
|
||||
index = binary_search_lcro(&nums, target);
|
||||
println!("目标元素 6 的索引 = {index}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user