CS 46B - Lecture 12
Pre-class reading
Linear Search
- Search for item in array
- Array is not sorted in any way
- What choice do we have? Look at all elements
- O(n)
- Ex. To search in 1000 elements, takes on average 500 steps
Binary Search
- Search for item in array
- Array is sorted
- Look at middle element
- Smaller than the one we search for?
- Search in first half
- Otherwise, search in second half
- Cut size of array in half in each step
- O(log n)
- To search in 1000 elements, takes < 10 steps
Lecture 12 Clicker Question 1
Binary search seems so much better than linear search. Should one sort the
array first to take advantage of it?
- Yes, always
- Only if one does at least n searches
- Only if one does at least n2 searches
- No, it's never a good idea. Linear search isn't that much slower.
Sorting Real Data
- Shocking revelation to CS instructors: Nobody pays you to sort
integers
- In real life, you sort file names, search results, birth records,
etc.
- Shocking revelation #2: Someone already wrote perfectly good sorting
functions
Arrays.sort
Arrays.binarySearch
Collections.sort
- Works with
Comparable objects, or supply
Comparator
- Extra twist in
binarySearch—reports insertion location as
negative number
Lecture 12 Clicker Question 2
You are given an ArrayList<Rectangle> and want to sort it
by increasing area. What do you do?
- Call
Arrays.sort and take advantage of the fact that
Rectangle implements Comparable
- Call
Arrays.sort and provide a suitable
Comparator object
- Call
Collections.sort and take advantage of the fact that
Rectangle implements Comparable
- Call
Collections.sort and provide a suitable
Comparator object
Summary
- Naive sorting is O(n2)
- Can do much better—merge sort is O(n log
n)
- Yes, that is much better.
- Searching in an unordered collection is O(n)
- In an ordered collection, searching is O(log n)
- Great to know that it's worth looking for efficient algorithms
- Big surprise—if you need to sort or search, someone has already
implemented efficient algorithms