DS14_Ch06c - 7 Quicksort - the fastest known sorting...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
§7 Quicksort -- the fastest known sorting algorithm in practice 1. The Algorithm void Quicksort ( ElementType A[ ], int N ) { if ( N < 2 ) return ; pivot = pick any element in A[ ]; Partition S = { A[ ] \ pivot } into two disjoint sets: A1={ a S | a pivot } and A2={ a S | a pivot }; A = Quicksort ( A1, N1) { pivot } Quicksort ( A2, N2); } 13 81 92 43 65 31 57 26 75 0 13 81 92 43 65 31 57 26 75 0 13 43 31 57 26 0 13 43 31 57 26 0 65 81 92 75 81 92 75 0 13 26 31 43 57 0 13 26 31 43 57 65 75 81 92 75 81 92 0 13 26 31 43 57 65 75 81 92 0 13 26 31 43 57 65 75 81 92 The best case T ( N ) = O( ) N log N The pivot is placed at the right place once and for all . 1/14
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
§7 Quicksort 2. Picking the Pivot A Wrong Way: Pivot = A[ 0 ] The worst case: A[ ] is presorted – quicksort will take O( N 2 ) time to do nothing A Safe Maneuver: Pivot = random select from A[ ] random number generation is expensive Median-of-Three Partitioning: Pivot = median ( left, center, right ) Eliminates the bad case for sorted input and actually reduces the running time by about 5%. 2/14
Background image of page 2
§7 Quicksort 3. Partitioning Strategy 8 1 4 9 0 3 5 2 7 6 5 9 2 8 6 9 i j > > j < < i i < i > j < i < i < > j i < Not too difficult if we carefully implement it… What if there is a key == pivot? How about stop i and j both and then swap? What will happen to the sequence: 1, 1, 1, …, 1 ? Uh-oh, there will be many dummy swaps… But hey! At least the sequence will be partitioned into two equal-sized subsequences. Good point! How about the other option – that neither i nor j stops? No swap… but then T ( N ) = … Then T ( N ) = O( N 2 ). So we’d better stop both i and j and take some extra swaps. 3/14
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
§7 Quicksort 4. Small Arrays Problem: Quicksort is slower than insertion sort for small N ( 20 ). Solution: Cutoff when N gets small ( e.g. N = 10 ) and use other efficient algorithms (such as insertion sort).
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 10/20/2011 for the course COMPUTER S 10586 taught by Professor Jilinwang during the Spring '09 term at Zhejiang University.

Page1 / 15

DS14_Ch06c - 7 Quicksort - the fastest known sorting...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online