CSE143 Program Example              handout #20
Code for merge sort
-------------------
// post: list is in sorted (nondecreasing) order
public static void sort(Queue list) {
    if (list.size() > 1) {
        Queue half1 = new LinkedList();
        Queue half2 = new LinkedList();
        int size1 = list.size() / 2;
        int size2 = list.size() - size1;
        for (int i = 0; i < size1; i++)
            half1.add(list.remove());
        for (int i = 0; i < size2; i++)
            half2.add(list.remove());
        sort(half1);
        sort(half2);
        mergeInto(list, half1, half2);
    }
}
// pre : result is empty; list1 is sorted; list2 is sorted
// post: result contains the result of merging the sorted lists;
//       list1 is empty; list2 is empty
public static void mergeInto(Queue result,
                             Queue list1,
                             Queue list2) {
    while (!list1.isEmpty() && !list2.isEmpty()) {
        if (list1.peek().compareTo(list2.peek()) <= 0)
            result.add(list1.remove());
        else
            result.add(list2.remove());
    }
    while (!list1.isEmpty())
        result.add(list1.remove());
    while (!list2.isEmpty())
        result.add(list2.remove());
}
Sample Execution on Linux Time-Sharing System (with n = 1 million)
------------------------------------------------------------------
linked list sort took 5.122 seconds
collections sort took 2.15 seconds
Ratio = 2.382325581395349
lists match and sort is stable