notes121

notes121 - CS 251 Class Notes For April 8, 10, and 12 By...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CS 251 Class Notes For April 8, 10, and 12 By Rod Weaver Quick Sort Implementation Radix Sort Straight Radix Sort Algorithm Bucket Sort String and Pattern Matching Brute Force Rabin-Karp String Matching Data Compression Huffman Encoding Trie Tries Standard Trie Quick Sort - Merge Sort is O(n log n) but it needs scratch memory at least the size of the sequence to sort. - Quick Sort can be done in place without scratch memory. - Quick Sort uses divide and conquer 1. Divide If s has 1 element, return Otherwise, choose an element x in array s to call pivot Divide s into 2 sets, L and G L = all elements less than or equal to x G = all elements greater than x 2. Call QuickSort(L) and QuickSort(G) r ecursively 3. Conquer Put elements of L , x , and G in s in that order Example: QuickSort( 7, 6, 2, 10, 4, 5, 9, 8 ) x = 8 L : ( 7, 6, 2, 4, 5 ) G : (10, 9 ) x = 5 x = 9
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
L : ( 2, 4 ) G : ( 7, 6 ) L : ( ) G : ( 10 ) x = 4 x = 6 L : ( 2 ) G : ( ) L : ( ) G : ( 7 ) 2 4 5 6 7 8 9 10 Implementation - Implement an "in place quicksort where extra space is not needed to store L and G at each step. Instead use only s . - Use array subranges to represent each set. - The last element in the array is the pivot . ( 85, 24, 63, 45, 17, 31, 96, 50 ) x = 50. - To separate ( divide ) s into L and G , we use l and r and iterate l form left to right until and element greater than the pivot is found. We iterate r from right to left until an element is found that is less than the pivot . Then, if both elements are found, swap them. - The process continues until l and r cross . 85, 24, 63, 45, 17, 31, 96, 50 x = 50 l = 85 (>50) r = 31 (<50) 31, 24, 63, 45, 17, 85, 96, 50 ----- -> l r <-- ------ 31, 24, 17, 45, 63, 85, 96, 50 ----- ----- ---- > l r <--- ---- ---- CROSS - Swap pivot with element pointed to by l . - Swap 63 and 50. 31, 24, 17, 45, 50, 85, 96, 63 // Sort a subrange of integers in an array s substring // at "left" ending at "right" void quickSortSubrange ( int * s, int left, int right ) { // return if subrange has one element if ( left > right ) { return; } // Use last element as pivot int x = s[ right ]; // Divide s into L and G int l = left; int r = right - 1;
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 8

notes121 - CS 251 Class Notes For April 8, 10, and 12 By...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online