{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

QuickSort

# Due due to partitioning quicksort is not stable

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: – Must always call itself with a smaller Must subarray subarray than the original – Does given pseudo-code guarantee this? 16 Quicksort – avoiding infinite recursion ! If If pivot is neither min nor max, there is at least one item in the left subarray and one item in the right right subarray ! If pivot is min (assuming unique) – “down” points to lb+1 “down” – “up” points to lb – Partition returns a value of lb for “pivot_idx” – Left subarray is empty – Right subarray has one item fewer 17 Quicksort – avoiding infinite recursion ! If pivot is max – “down” points to ub – “up” points to ub – Partition returns a value of ub for “pivot_idx” – Left subarray has one item fewer – Right subarray is empty ! Thus, Thus, all calls to qsort() specify subarrays 18 of of smaller size (i.e., no infinite recursion) Quicksort: Time – best case and average case Best Best and average cases: qsort() uses non-poor pivots non! Uses n comparisons (and less interchanges) to Uses comparisons partition array into two subarrays of size n/2 ! Then on each subarray, it uses n/2 comparisons, etc. Then ! Total, it uses: Total, n+ “Binary “Binary (n/2 + n/2) + /2 /2) Tree” Tree” ((n/4 + n/4) + (n/4 + n/4)) + (( /4 /4 /4)) … comparisons comparisons ! In other words, n comparisons at each recursion depth In ! Recursion depth (divide and conquer) is log2 n Recursion ! Thus, it has n * log2 n comparisons Thus, ! Result: Result: O(n log2 n) 19 Quicksort: Time – worst case Worst Worst case: Always chooses poor pivot ! ! ! Uses comparisons Uses n comparisons (and less interchanges) to partition file into two subfiles of s...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online