Interactive Data Structure Visualizations
Efficient Sorts

The efficient sorting algorithms are important, not because of their simplicity, but because of their efficiency. The efficiency of the merge sort and quick sort is O(n log n).

As with the majority of sorting algorithms, the swap operation is fundamental to the quick sort. The quick sort is a recursive algorithm. At each step, one element is placed into its proper position, then the remaining subarrays on each side are sorted. When you watch the animation, there are several things you should notice to help you understand the behavior of this algorithm. The bar that is highlighted in black is the bar that it being positioned at each step. It is the left-most bar of the subarray that is being sorted. To position that bar the array must be arranged so that all values to its left are less than or equal to it and all those to its right are greater than or equal to it. To achieve this result, the array is examined from the left and from the right. The arrows at the bottom of the screen move toward each other as this process continues. When a value on the left is encountered that is greater than the value to be positioned, it stops. When a value on the right is encountered that is less than the value to be positioned, it stops. These values are then swapped. This process continues until the arrows meet. At this time, the value highlighted in white can be moved into its proper position. The remaining subarrays are then both sorted in the same fashion.

Like the quick sort, the merge sort is recursive. An important difference is that in the quick sort the work is done moving into the recursion, while in the merge sort all the work, which is the merging, is done backing out of the recursion. The array is recursively divided in half until the two halves are single element arrays. Each pair of halves is merged after they have been sorted. Notice the black lines at the bottom of the screen. They illustrate the division process. When a line appears, all elements within that line are sorted. The entire array is sorted when a black line extends across the entire screen.