42B. An Efficient Sorting Algorithm: Merge Sort

We can do much better than insertion sort. To sort a nonempty list L of length n, break L into halves, where L1 is the first half and L2 is the second half. Sort lists L1 and L2. So now we have two sorted lists. All that is left to do is to merge those lists together into a single sorted list, taking advantage of the facts that they are already sorted. The following diagram illustrates.

This algorithm, called Merge Sort, can be shown to take time Θ(n log2(n)) in the worst case.

Θ(n log(n)) is much better than Θ(n2). If n is 10,000, n2 is 100,000,000, but nlog(n) is only about 130,000. (You should be able to show that log2(10,000) ≈ 13. Use the fact that log2(1000) is very close to 10.)