Let a1,a2,...,an be a list of real numbers. The basic steps of Quicksort are as follows:
- Pick an element x as the pivot element.
- Partition the list into three sublists,
R1 ={ai |ai <x}, R2 ={ai |ai =x}, andR3 ={ai |ai >x}. - Sort the elements in R1 and R3 recursively, by invoking Quicksort (as the elements in R2 are already sorted.)
- Combine the three sorted lists R1, R2, R3 in this order into a sorted
sequence.
评价:
- The running time of Quicksort is O(n^2) in the worst case.
- The running time is O(nlogn) in an average case: either for a random input, or using a random pivot.
- To make the worst case unlikely, use a random pivot or follow some rule justified by experience such as “median of three”.
- 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.
- Implemented carefully,Quicksort is usually the fastest method for sorting arrays.
The code in python3 is here
网友评论