3.11 Binary Search

7 阅读1分钟

1. Exam Points

  • Data must be in sorted order (ascending or descending) to use the binary search algorithm.
  • 使用二分查找算法,数据必须是排序的,升序或降序都可以.
  • Binary search is often more efficient than linear search in most cases.
  • Sorted data set can be data set of strings, numbers.
  • Elements in a data set can be duplicate. [1, 1, 2, 2, 3, 3, 3]
  • Determine the maximum elements to be examined to find a value: find the minimum x that satisfies 2^x>n.
    • 确定在一个数据集中查找一个值需要检查的元素的最大数量: 寻找满足 2x > n (元素个数) 的最小 x
  • Determine the number of rounds of cutting in half: x-1.
    • 确定在一个数据集中查找一个值需要折半的次数: x-1

2. Knowledge Points

(1) Linear Search vs. Binary Search

  • Sequential/linear search (顺序/线性查找) check each element in order until the desired value is found or all elements have been accessed.
    image.png
    • Code implementation:
      image.png
  • The binary search (二分查找) algorithm starts at the middle of a sorted data set of numbers and eliminates half of the data, this process repeats until the desired value is found or all elements have been eliminated.
  • Exclusions: Specific implementations of the binary search are outside the scope of the course and the AP Exam.
  • Data must be in sorted order to use the binary search algorithm.
  • Binary search is often more efficient(not always) than sequential/linear search (顺序/线性查找) when applied to sorted data.

(2) Understand Binary Search

  • Process of binary search: when the number of elements is odd
    • image.png
  • Process of binary search: when the number of elements is even
    • select the middle left element as the middle element.
    • image.png
  • Conclusion:
    • minimum number of elements to be examined: 1
    • maximum number of elements to be examined: find the minimum x that satisfies 2^x>n
      • ⌊log2(n)⌋ + 1 或者 寻找满足 2^x > n (元素个数) 的最小x,也就是寻找满足2的x次方>n的最小x**

3. Exercises