notes122

notes122 - QUICKSORT MergeSort is O(nlogn but it needs...

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

View Full Document Right Arrow Icon
4/8/2002 QUICKSORT - MergeSort is O(nlogn) but it needs scratch memory to work at least the size of the sequence to sort. - QuickSort can be done "in place" without the need of scratch memory. - QuickSort uses "divide and conquer". Algorithm : quickSort(S) Input : unsorted array S. Output: sorted array S. 1. Divide : - if s has only one element, return - Otherwise, choose an element x called pivot and divide S into sets L and G such that: all elements of L are less than or equal to x and each element in G is greater than x . 2. Recur : - call quickSort(L) and quickSort(G). 3. Conquer : - put elements of L, X, G in S in that order. - Example: quickSort( 7, 6, 2, 10, 4, 5, 9, 8) Implementation: - we implement an in place quickSort where we do not need extra space to store L & G at each step. Instead, we only use S. - we will use array sub ranges to represent each step. - the last element in each step is used as the pivot. - o iterate l from left to right until an element greater than the pivot is found.
Background image of page 1

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

View Full Document Right Arrow Icon
o iterate r from right to left until we find an element less than the pivot. o if both elements are found, swap them. - 85 ( l ), 24, 63, 45, 17, 31, 94 ( r ), 50 ( x ). [85>50, no more right iterations for l . 91 not less than 50, continue right to left iteration for r .] 85 ( l ), 24, 63, 45, 17, 31 ( r ), 94, 50 ( x ). [since 85>50 and 31<50, we swap the elements.] 31 ( l ), 24, 63, 45, 17, 85, 94 ( r ), 50 ( x ). [31 not greater than 50, 94 not less than 50. continue iterations.] 31, 24 ( l ), 63, 45, 17, 85 ( r ), 94, 50 ( x ). [24 not greater than 50, 85 not less than 50. continue iterations.] 31, 24, 63 ( l ), 45, 17 ( r ), 85, 94, 50 ( x ). [65>50 and 17<50, swap them.] 31 ( l ), 24, 17, 45, 63, 85, 94 ( r ), 50 ( x ). [Similar iterations continue until l and r both equal 63. Then 63 and 50 swap to produce the following sequence]. (L){31, 24, 17, 45},
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.

{[ snackBarMessage ]}

Page1 / 6

notes122 - QUICKSORT MergeSort is O(nlogn but it needs...

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