This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: Heather O'Cull CS 251 Notes: Week of April 8-12 MONDAY QuickSort MergeSort is O(nlog(n)) but it needs scratch memory to work at least the size of the squence to sort, QuickSort can be done "in place" without the need of scratch memory. QuickSort uses "divide and conquer" too. Algorithm quicksort(s) Input: unsorted array s Output: sorted array s 1. Divide If s has only 1 element: return Otherwise, choose an element x in array s called the pivot . Divide s into 2 sets: L and G such that L is all elements <= to x and G is all elements > x. 2. Call quicksort(L) and quicksort(G) recursively Assume they are now sorted 3. Conquer Put elements of L, x, G in s (in that order) Example: quicksort(7, 6, 2, 10, 4, 5, 9, 8 ) pivot is the last element (the pivot is very important) L(7, 6, 2, 4, 5 ) 8 G(10, 9 ) L(2, 4 ) 5 G(7, 6 ) 8 L( ) 9 G(10) L(2) 4 G( ) 5 ( ) 6 (7) 8 9 (10) 2 4 5 6 7 8 9 10 if pivot divides the group into equal sizes then it is O(nlogn) if you choose the pivot at random, likely to get a number near the middle Implementation we implement an "in place" quicksort where we don't need extra space to store L and G at each step. Instead we use only s we will use array sub ranges to represent each set the last element in the array is used as the pivot to separate (divide) L and G we use l and r (pointers to the array) and iterate l from left to right until we find an element greater than the pivot. We iterate r from right to left until we find an element less than the pivot. Then if both elements are found- we swap them. the process continues until l and r cross (i.e. l > r) swap pivot with element pointed by l (will point to element > pivot) l85 24 63 45 17 31 r96 x50 move l to the right until it comes to an element greater than 50 and move r until it comes to an element less than 50 l85 24 63 45 17 r31 96 x50 swap and repeat 31 24 l63 45 r17 85 94 x50 swap and repeat 31 24 17 r45 l63 85 94 x50 swap 31 24 17 l45 r63 85 94 x50 swap 63 and 50 since l > r L(31 24 17 45) x50 G(85 96 63) //Sort a sub range of integers in an array S starting at "left" and ending at "right"...
View Full Document