|
|
|
|
|
m = n / 2
sort a[1..m] recursively
sort a[m+1..n] recursively
copy a[m+1..n] to temp space
merge
If using O(n) extra space is of no concern, then merge sort is an excellent choice. It is simple to implement, and it is the only stable O(n·lg(n)) sorting algorithm.
There do exist linear time in-place merge algorithms (for the last step of the algorithm), but they are extremely complex. The complexity is justified for applications such as external sorting where the extra space is not available, but one of the important properties (stability) may be lost.
When sorting linked lists, merge sort requires only O(1) extra space. Given its many other advantages, merge sort is an excellent choice for sorting linked lists.
to restart the animations.
Algorithms in Java, Parts 1-4, 3rd edition by Robert Sedgewick. Addison Wesley, 2003.