QuickSort

uses comparisons uses n comparisons and less

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: ize n-1 and 1 Then it works on the larger subfile Total, Total, it requires: (n-1) + (n-2) + … + 1 = n*((n + 1) / 2 2) 1) = n2/2-n/2 comparisons /2! Result: Result: O(n2) ! Note: Note: max recursion depth is n = O(n) 20 Quicksort: Memory complexity Additional Additional memory is needed for the stack in function calls (and it is proportional to the the maximum recursion depth) ! Expect case: O(log n) Expect (log ! Worst case: O(n) Worst 21 Quicksort: improvements ! Selecting Selecting a good pivot by random selection selection of pivot, median of median, or search search for median ! Reduce Reduce overhead when subarray becomes small by employing other sorting algorithms ! Fewer recursions by using tail recursion 22 Quicksort: Pivot Selection Strategies ! ! ! ! ! Median as pivot (O(n) but not practical) Median-ofMedian-of-three: median of first, middle, last elements elements Median-of-three Median-of-three as the first pivot, and means of of subarrays as subsequent pivots (Meansort) Random position: O(n log n) with high probability log Middle Middle element (Bsort) – When incrementing and decrementing “down” and “up”, When perform perform comparisons and swaps of neighbors as in bidirectional directional bubble sort to find largest item of left subarray and least least item of right subarray – Detect sortedness – A subarray of size two is sorted – To sort a subarray of size three, only one comparison is needed 23 Quicksort: Quicksort: Median-of-three // find median of a, b, and c if (a < b) if if (b < c) median median = b; else if ( a < c) median = c; else median = a; else if (c < b) median = b; else if (c < a) median = c; else median = a; 24 Quicksort: Quicksort: small/sorted arrays ! Sort Sort small arrays (e.g., 2 or 3) by explicit comparisons comparisons and exc...
View Full Document

This document was uploaded on 03/06/2014 for the course ECE 368 at Purdue.

Ask a homework question - tutors are online