Skip to content

Commit

Permalink
Update 01.Array-Binary-Search-01.md
Browse files Browse the repository at this point in the history
  • Loading branch information
itcharge committed May 8, 2024
1 parent 14a4b28 commit 40158e2
Showing 1 changed file with 7 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@

举个例子来说,以在有序数组 $[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]$ 中查找目标元素 $6$ 来说,使用二分查找算法的步骤如下:

1. **确定查找范围**:初始时左边界 $left$ 为 $0$(数组的起始位置),$right$ 为 $10$(数组的末尾位置)。此时查找范围为 $[0, 10]$。
2. **计算中间元素**中间元素下标位置为 $5$,对应元素为 $nums[5] == 5$。
3. **比较中间元素**:因为 $6 > nums[5]$,所以目标元素可能在右半部分,更新左边界为中间元素的后一个位置,即 $left = 5$。此时查找范围为 $[5, 10]$。
4. **计算中间元素**中间元素下标位置为 $7$,对应元素为 $nums[7] == 7$。
5. **比较中间元素**:因为 $6 < nums[7]$,所以目标元素可能在左半部分,更新右边界为中间元素的前一个位置,即 $right = 6$。此时查找范围为 $[5, 6]$。
6. **计算中间元素**中间元素下标位置为 $5$,对应元素为 $nums[5] == 5$。
7. **比较中间元素**:因为 $5 == nums[5]$,正好是我们正在查找的目标元素,此时返回中间元素的下标位置,算法结束。
1. **确定查找范围**:初始时左边界 $left = 0$(数组的起始位置),$right = 10$(数组的末尾位置)。此时查找范围为 $[0, 10]$。
2. **计算中间元素**中间元素下标位置 $mid = (0 + 10) \div 2 = 5$,对应元素为 $nums[5] == 5$。
3. **比较中间元素**:因为 $6 > nums[5]$,所以目标元素可能在右半部分,更新左边界为中间元素的后一个位置,即 $left = 6$。此时查找范围为 $[6, 10]$。
4. **计算中间元素**中间元素下标位置 $mid = (6 + 10) \div 2 = 8$,对应元素为 $nums[8] == 8$。
5. **比较中间元素**:因为 $6 < nums[8]$,所以目标元素可能在左半部分,更新右边界为中间元素的前一个位置,即 $right = 7$。此时查找范围为 $[6, 7]$。
6. **计算中间元素**中间元素下标位置 $mid = (6 + 7) \div 2 = 6$(向下取整),对应元素为 $nums[6] == 6$。
7. **比较中间元素**:因为 $6 == nums[6]$,正好是我们正在查找的目标元素,此时返回中间元素的下标位置,算法结束。

于是我们发现,对于一个长度为 $10$ 的有序数组,我们只进行了 $3$ 次查找就找到了目标元素。而如果是按照顺序依次遍历数组,则在最坏情况下,我们可能需要查找 $10$ 次才能找到目标元素。

Expand Down

0 comments on commit 40158e2

Please sign in to comment.