[   ^ to index...   |   <-- previous   |   next -->   ]

O(n log n) sorts

Mergesort

IDEA: "If there are two or fewer elements in the array, order them and return. If the array has more than two elements, break the array in half, recursively sort the two halves, and then merge them."

10 19 3 120 42 33 81 14

               

               

               

               

               

Quicksort

IDEA: "Select an element X, called the pivot. Divide all the other elements into two piles: all elements <= X, and all elements > X. We now know exactly which location X should go into (why?), so put it there and sort the remaining two piles."

In practice, we do not simply loop through each element and consign it to a "left" or "right" pile. Instead, we observe that many items will already be in their proper place, either to the left or the right of the expected pivot position.

Therefore, we loop down the left and right sides until we find two elements that we need to swap, and then we swap them. We proceed like this until our "left" and "right" cursors meet, and the meeting point will be where we place the pivot element.

In practice, quicksort is the fastest of the O(nlogn) sorts most of the time.

Caveats:


Last modified: Tue Aug 8 10:25:19 PDT 2000