1. Exam Points
- Data must be in
sorted order(ascending or descending) to use thebinary search algorithm.- 使用二分查找算法,数据必须是排序的,升序或降序都可以.
- Binary search is
often more efficientthan 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 examinedto 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 orderuntil the desired value is found or all elements have been accessed.
- Code implementation:
- Code implementation:
- The
binary search(二分查找) algorithmstarts at the middle of a sorted dataset of numbers andeliminates 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 searchisoften more efficient(not always)than sequential/linear search (顺序/线性查找) when applied to sorted data.
(2) Understand Binary Search
Processof binary search: when thenumber of elements is odd
-
Processof binary search: when thenumber of elements is even
- select the
middle leftelementasthemiddleelement. -
- select the
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**