{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Sort sort small arrays eg 2 or 3 by explicit

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: hanges ! Simple Simple insertion faster for smaller arrays, a common optimization is to use it for subarray subarray with fewer than about 25 items ! For For sorted arrays, even bubble sort is faster faster than quicksort – Use Bsort for best “compromise” 25 Quicksort: Tail Recursion ! Any recursive function of the form: function (a, b, c) { ... function (x, y, z); } Can be rewritten as: function (a, b, c) { while (TRUE) { ... a = x; b = y; c = z; } } (some compilers do this automatically) 26 Quicksort: Quicksort: Tail Recursion qsort (r, lb, ub) { ... qsort qsort (r, lb, down - 1); qsort (r, down, ub); } becomes qsort (r, lb, ub) { while (TRUE) { ... qsort qsort (r, lb, down - 1); lb = down; // upper = upper } } 27 Quicksort: Tail Recursion ! Reduces Reduces required max stack size ! In In qsort(): perform the recursive call for the the smaller subarray first – Smaller subarray usually requires less stack Smaller space (fewer recursions) – With tail recursion and sorting the smaller With subarray first, the worst case is O(log n) (log because the smaller subarray is a most size n/2 and the larger subarray does not require a /2 function function call (it would use iteration) 28 An An Improved Quicksort Function Function qsort (r, lb, ub): qsort_tr(r, qsort_tr(r, lb, ub); insertion_sort(r, lb, ub); Function qsort_tr(r, lb, ub): while while ub – lb > smallsize pivot_idx = partition(r, lb, ub); if pivot_idx < (lb+ub)/2 qsort_tr(r, lb, pivot_idx-1); pivot_idxlb = pivot_idx+1; else qsort_tr(r, pivot_idx+1, ub); ub = pivot_idx-1 pivot_idx- 29 Quicksort: Summary ! Good pivots are necessary – Fortunately, we have O(n) time to choose it Fortunately, – Optimal pivot would split file evenly ! Median-of-three (Meansort) is usually of-three good good enough (and faster) ! Bad Bad quicksort implementation performs poor for (almost) sorted input and many equal equal keys (no good pivot exists) 30...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online