Version 5.2.11
Handouts: BinarySearch.java.
Two methods for searching arrays.
int.Whenever we can reduce a problem's size by halving it instead of subtracting one, we get a big gain: we reduce a factor of N to a factor of log N.
Examples:
The idea:
Current element
|
V
+--------------------+--+-----------------------------+
|sorted region | | unsorted region |
+--------------------+--+-----------------------------+
For each element from first to last: insert the element into the correct position in the sorted region, increasing that region's size by one. The sorted region is initially just a single element, xs[0]; at the end, it is the entire array.int) (file: Search.java)Insert-sort with Romanian folk dance (YouTube, 4:04)
Comparable Interfaceint, to arrays of any type of object for which comparison makes sense.2compareTo method: a.compareTo(b) returns:
a < ba is equal to b. (Should agree with the equals method.)a > b Does not necessarily return −1, 0, or +1.Comparable<T>, since an object of type T can be expected to compare itself only to objects of the same type: numbers to numbers, strings to strings, dice to dice, for example.Using the interface for searching and sorting arrays of comparable elements: declare the elements <E extends Comparable<E>> (why?), for example,
public class SortableArrayList<E extends Comparable<E>> {
...
}
(see SortableArrayList.java, SortableLinkedList.java)
Exercise: modify the recursive binary search for an array of Comparable (say String or Integer) objects.
Strictly speaking, this is not a generalization, because int is a primitive type: an int value is not an object. Of course we can substitute an Integer object. But int itself is not Comparable. In contrast, consider the Haskell Ord typeclass, which specifies a method of comparison resulting in a value of LT (less than), EQ (equal), or GT (greater than). The Haskell Int type is an instance of Ord, though it is what we would call a primitive type in Java terms; it's not an object (Haskell does not have objects in the same sense that Java does), but it's certainly not a structured type either.↩