8. Quick Sort --- An application of the linear selection algorithm

Let a1,a2,...,an be a list of real numbers. The basic steps of Quicksort are as follows:

  1. Pick an element x as the pivot element.
  2. Partition the list into three sublists,
    R1 ={ai |ai <x}, R2 ={ai |ai =x}, andR3 ={ai |ai >x}.
  3. Sort the elements in R1 and R3 recursively, by invoking Quicksort (as the elements in R2 are already sorted.)
  4. Combine the three sorted lists R1, R2, R3 in this order into a sorted
    sequence.

评价:

  1. The running time of Quicksort is O(n^2) in the worst case.
  2. The running time is O(nlogn) in an average case: either for a random input, or using a random pivot.
  3. To make the worst case unlikely, use a random pivot or follow some rule justified by experience such as “median of three”.
  4. Small lists (less than 10–20 elements) are sorted faster by insertion sort. Therefore, use insertion sort on all small sublists rather than partitioning further.
  5. Implemented carefully,Quicksort is usually the fastest method for sorting arrays.
推导过程

The code in python3 is here

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容