到目前为止, 我们已经学习到了插入排序, 冒泡排序, 选择排序(selection)。 这些排序算法都是comparision based sorting algorithms(即涉及到元素大小的比较来决定元素的先后顺序)。 而且算法的时间复杂度上均为O(n^2)。但是comparision based 的排序算法远非这几个算法。 而且可以通过利用其它的一些手段(例如divide and conquer technique, 分治法)实现对基于比较的排序算法的时间复杂度降低到O(nlogn)。 其中一个就是quick sort, 故名思议, quick sort 的速度很快。
quick sort 可以采用一个in-place partition algorithm实现。quck sort 在递归的时候仅需要占用stack额外空间为O(logn)。
quick sort 是一个divide and conquer algorithms。 快排序通过首先对一个large array 分成2个小的subarrays: 即the low elements and the high elements。 Quick sort 可以recursively sort the subarrays。
快排序的步骤如下:
- Pick an element, called a pivot, from the array.
- Reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position(也就是说, 这个pivot在其最后排好序的actual place). This is called the partition operation.
- Recursively apply the above steps to the sub-array of elements with smaller valu