The Sorted Array
This chapter builds binary search over a sorted array, implemented first iteratively and then recursively, and derives its step count against linear search’s . It then builds a SortedArray that maintains a sorted-order invariant, implementing add, search, and remove with binary search.
After reading this chapter, you should be able to:
- Explain why keeping data in sorted order lets you search much faster, by repeated halving, than the linear scan an unsorted collection needs
- Implement and trace binary search over a sorted array, returning an index (or
-1), and refine it to report the insertion point where a missing value belongs - Write a search recursively with a base case and a recursive case, and explain why moving toward the base case makes it terminate
- Hide a recursion’s index/bounds parameters behind a public method that delegates to a private overloaded helper (information hiding)
- Derive that binary search takes about steps, and compare how linear () and binary () search scale as the input grows
- Build a
SortedArraythat maintains a sorted-order invariant, implementing add, search, and remove with binary search and explaining why the invariant determines which operations the contract can offer
You can download the accompanying code for this chapter: starter and solution.
Sections
- Why Keep It Sorted?
- Binary Search
- Binary Search, Recursively
- Searching Half the Array
- Passing the Bounds
- The Base Case
- The Base Case and the Recursive Case
- Recursive Linear Search
- A Public Method and a Private Helper
- A Helper for Binary Search
- Recursive vs. Iterative
- Counting the Steps in Binary Search
- Linear vs. Binary Search, Side by Side
- The SortedArray
- Adding in Order
- Searching with Binary Search
- Removing
- Should we offer a set operation?