algo_ch7_quick_sort

First subarray all values in second returns the index

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: lt: Two subarrays All values in first subarray ≤ all values in second Returns the index of the “pivot” element separating the two subarrays 9 Partition Code Partition(A, p, r) { x = A[r] // x is pivot i=p-1 for j = p to r – 1 { do if A[j] <= x then { i=i+1 exchange A[i] ↔ A[j] } } exchange A[i+1] ↔ A[r] return i+1 } partition() runs in O(n) time 10 Partition Example A = {2, 8, 7, 1, 3, 5, 6, 4} i pj r pi j r 28713564 28713564 pi pi j r j r 28713564 2 8 71356 4 p p i j r i j r 2 178356 4 21 38756 4 13 p p i j r 2 138756 4 13 p i r 21387564 13 i r 21347568 13 11 Partition Example Explanation Red shaded elements are in the first partition Red with values ≤ x (pivot) Gray shaded elements are in the second Gray partition with values ≥ x (pivot) The unshaded elements have no yet been put The in one of the first two partitions The final white element is the pivot The 12 Choice Of Pivot Pivot is rightmost element in list that is to be Pivot rightmost sorted When sorting A[6:20], use A[20] as the pivot Textbook implementation does this Randomly select one of the elements to be sorted Randomly as the pivot When sorting A[6:20], generate a random number r in the range [6, 20] Use A[r] as the pivot 13 Choice Of Pivot Median-of-Three rule - from the leftmost, middle, Median rule and rightmost elements of the list to be sorted, select the one with median key as the pivot When sorting A[6:20], examine A[6], A[13] ((6+20)/2), and A[20] Select the element wit...
View Full Document

This document was uploaded on 11/11/2013.

Ask a homework question - tutors are online