lecture-12

# Element in the list put values smaller than the pivot

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:  ­ Fall 2010 12 6 10/12/10 Comparison of Sorting Algorithms Best Case Average Case Worst Case Selec3on Sort O(n2) O(n2) O(n2) Bubble Sort O(n) O(n2) O(n2) Inser3on Sort O(n) O(n2) O(n2) O(nlogn) O(nlogn) O(nlogn) Mergesort Quicksort Heapsort Treesort CPSC 223  ­ ­ Fall 2010 13 CPSC 223  ­ ­ Fall 2010 14 Quicksort 7 10/12/10 Quicksort [Hoare, 1962] •  Another “divide and conquer” approach •  The basic idea: –  Pick a “pivot” element in the list –  Put values smaller than the pivot on the left –  Put values larger than the pivot on the right –  Put pivot value in its ﬁnal sorted position –  Repeat on the left and right sublists Par33on and Place Pivot Pick pivot Ini3al list: 29 10 32 13 (n=4) 29 10 13 32 29 10 32 13 13 10 29 32 P1 Repeat on Sublists 13 10 29 32 P2 10 13 29 32 CPSC 223  ­ ­ Fall 2010 15 Quicksort 29 10 32 13 Ini3al list (n=4) Par22on 13 10 Par22on 10 29 pivot 32 n = 2, n = 1 n = 1, n = 0 13 pivot CPSC 223  ­ ­ Fall 2010 16 8 10/12/10 Quicksort (based on textbook) void Quicksort(Entry theArray, int ﬁrst, int last) { if(ﬁrst &lt; last) { int pivotIndex = Partition(theArray, ﬁrst, last); // quicksort ﬁrst half Quicksort(theArray, ﬁrst, pivotIndex – 1); // quicksort second half Quicksort(theArray, pivotIndex + 1, last); } } Note we do not include the pivot element i...
View Full Document

Ask a homework question - tutors are online