{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

algo_ch7_quick_sort

Combine unlike merge sort no work needed since

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

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: alls to quicksort. Combine: unlike merge sort, no work needed since Combine the subarrays are sorted in place already. 4 Quicksort The basic algorithm to sort an array A consists of The the following four easy steps: If the number of elements in A is 0 or 1, then return Pick any element v in A. This is called the pivot Partition A-{v} (the remaining elements in A) into two disjoint groups: A1 = {x ∈ A-{v} | x ≤ v}, and A2 = {x ∈ A-{v} | x ≥ v} return { quicksort(A1) followed by v followed by quicksort(A2)} 5 Quicksort Small instance has n ≤ 1 Small Every small instance is a sorted instance To sort a large instance: To select a pivot element from out of the n elements Partition the n elements into 3 groups left, middle Partition and right The middle group contains only the pivot element All elements in the left group are ≤ pivot All elements in the right group are ≥ pivot Sort left and right groups recursively Sort Answer is sorted left group, followed by middle Answer group followed by sorted right group 6 Example 6 2 8 5 11 10 4 1 9 7 3 Use 6 as the pivot 2 5 4 1 3 6 7 9 10 11 8 Sort left and right groups recursively 7 Quicksort Code Quicksort(A, p, r) { if (p < r) { q = Partition(A, p, r) Quicksort(A, p , q-1) Quicksort(A, q+1 , r) } } Initial call is Quicksort(A, 1, n), where n in the Initial Quicksort length of A 8 Partition Clearly, all the action takes place in the Clearly, partition() function partition() Rearranges the subarray in place End resu...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online