Notes for July 13, 2005

Topics

Comparable interface

With primitives like ints, it's easy to compare their values against one another, since Java has operators to do that like < and >. However, for objects, Java has no way of knowing how the programmer wants objects of a certain class to relate to one another. Enter the Comparable interface. The Comparable inteface is defined as follows:
    public interface Comparable {
        public int compareTo(Object o);
    }
The compareTo method should have the behavior such that if you made the call x.compareTo(y), then

compareTo returns when
 some negative integer x < y
 0 x = y
 some positive integer x > y

Sorting

Of the various sorting methods out there, we will only be interested in merge sort for now. The code is on handout #15. The running time for merge sort is O(n log n). To see why, merge sort divides the list in half repeatedly until it reaches a one-element list (see picture below). How many times can it divide a list of n elements in half? The answer is log2n (If you don't understand why, make sure you ask!). After it sorts each half, it merges them together. If each list has n/2 elements (at the second level in the picture below), then the merge operation takes n steps, because it need only look at each element once while performing the merge. Notice that at the third level, two merges are performed. Each merge operates on lists of n/4 elements. That means each merge takes n/2 time. Since there are two merges, the total time at that level is n time. At the level below that, there are four merge operations performed, and each merge takes n/4 time for a total time of (drumroll, please) n time. Since there are log2n levels and each level takes n time, the total time is O(n log2n). We can omit the base (2) and just write it as O(n log n).

(image linked from http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Sorting/mergeSort.htm)