Algorithm(Robert Sedgewick)-Day06 | Quicksort

Basic plan
Shuffle the array.
Partition so that, for some j
entry a[j] is in plac
no larger entry to the left of j
no smaller entry to the right of j
Sort eah piece recursively

Phase I.
Repeat until i and j pointers cross
Scan i from left to right so long as (a[i] < a[lo])
Scan j from right to left so long as (a[j] > a[lo])
Exchange a[I] with a[j]
Phase II.
When pointers cross.
Exchange a[lo] with a[j]

Partitioning in-place. Using an extra array makes partioning easier(and stable), but is not worth the cost.

Using an extra
Terminating the loop. Testing whether the pointers cross is a bit trickier than it might seem.

Staying in bounds.

Preserving randomness. Shuffling is needed for performance guarantee.

Equal keys. When duplicates are present, it is (counter-intuitively) better to stop on keys equal to the partitioning item’s key.

Good algorithms are better than supercomputers.
Great algorithms are better than good ones.

Proposition. The average number of compares Cn to quicksort an array of N distinct keys is ~2NlnN and the number of exchanges is ~1/3NlnN

Random shuffle.

Probabilistic guarantee against worst case.
Basis for math model that can be validated with experiments.

Quicksort in an in-place sorting algorithm.
Quicksort is not stable.

Quicksort: practical improvements
Insertion sort small subarrays.
Quicksort is slower than insertion sort for tiny subarrays.
Cutoff to insertion sort for =10 items
Note: could delay insertion sort until one pass at end.

Median of sample.
Best choice fo pivot item = median.
Estimate true median by taking median of sample.
Median-of-3 (random) items.

Selection
Goal. Given an array of N items, find the Kth smallest item.

Applications.
Order statistics.
Find the ‘‘top k’’.

Partition array so that:
Entry a[j] is in place.
No larger entry to the left of j.
No smaller entry to the right of j.

Repeat in one subarray, depentding on j; finished when j equals k.

Duplicate keys.

Sorting applications.

你可能感兴趣的:(Algorithm)