Sorting

Sorting - Sorting Selection Sort Worst case: O(n2) Best...

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

View Full Document Right Arrow Icon
Sorting Selection Sort Worst case: O(n 2 ) Best case: O(n 2 ) BAD 2 -1 4 5 -6 find maximum and switch with last 2 -1 4 -6 5 repeat until single element # of comparisons (n-1) + (n-2) + … 1 = n(n-1)/2 = O(n 2 ) Insertion Sort worst case: O(n 2 ) best case: O(n) 2 -1 4 5 -6 assume first block is sorted, compare the one next to it and insert it in the proper position -1 2 4 5 -6 -1 2 4 5 -6 -1 2 4 5 -6 -6 -1 2 4 5 # of comparisons - worst case: 1+2+3+4+…(n-1) = n(n-1)/2 = O(n 2 ) # of comparisons - best case: 1+1+1+…+1 = (n-1) = O(n) do that (n-1) times Quicksort - Works on arrays “divide and conquer” break array into two parts and recursively sorts the two parts, can do better than selection or insertion while A[left] < A[0] left++ while A[right] !< A[0] right-- Switch A[left] with A[right] left++ right--
Background image of page 1

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

View Full DocumentRight Arrow Icon
REPEAT until left and right cross over Switch A[0] with A[right] 0 1 2 3 4 5 6 7 8 2 9 8 -5 -4 15 1 18 22 A[0] = pivot A[pivot + 1] = left = 1 A[length - 1] = right = 8 left stop at 1 right stop at 6 0 1 2 3 4 5 6 7 8 2 1 8 -5 -4 15 9 18 22 left = 2 right = 5 … left stop at 2, right stop at 4 0 1 2 3 4 5 6 7 8 2 1 -4 -5 8 15 9 18 22 right= 3 left = 4 switch 0 with 3 0 1 2 3 4 5 6 7 8 -5 1 -4 2 8 15 9 18 22 recursively quicksort left and right of pivot Quicksort Tree 2 9 8 -5 -4 15 1 18 22 split at -4; # comparisons = 8 (n-1) [-5|1|-4] [2] [8|15|9|18|22] split at -5 #c = 2 [-5] [1|-4] [8] [15|9|18|22] split at 1; c=1 split at 15; #c = 3 [-4] [1] [9] [15] [18|22] split at 18 [18] [22] -5 -4 1 2 8 9 15 18 22
Background image of page 2
Worst case (array is already sorted) n, n-1, n-2, …, 1 n + (n-1) + (n-2) + … + 1 = O(n 2 ) Best case # of comparisons level 1: ~n level 2: (n/2 -1) + (n/2 -1) sum of all levels: O(n log n) worse than insertion sort’s best case Average case: O(n log n)
Background image of page 3

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

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 03/29/2012 for the course CS 112 taught by Professor Sesh during the Spring '07 term at Rutgers.

Page1 / 8

Sorting - Sorting Selection Sort Worst case: O(n2) Best...

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

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