Sorting: What Makes It Hard? Chapter 7 in DS&AA Chapter 8 in DS&PS
Sorting: What Makes It Hard? Chapter 7 in DS&AA Chapter 8 in DS&PS
Sorting: What Makes It Hard? Chapter 7 in DS&AA Chapter 8 in DS&PS
Chapter 7 in DS&AA
Chapter 8 in DS&PS
Insertion Sort
• Algorithm
– Conceptually, incremental add element to sorted array
or list, starting with an empty array (list).
– Incremental or batch algorithm.
• Analysis
– In best case, input is sorted: time is O(N)
– In worst case, input is reverse sorted: time is O(N2).
– Average case is (loose argument) is O(N2)
• Inversion: elements out of order
– critical variable for determining algorithm time-cost
– each swap removes exactly 1 inversion
Inversions
• What is average number of inversions, over all inputs?
• Let A be any array of integers
• Let revA be the reverse of A
• Note: if (i,j) are in order in A they are out of order in revA.
And vice versa.
• Total number of pairs (i,j) is N*(N-1)/2 so average
number of inversions is N*(N-1)/4 which is O(N2)
• Corollary: any algorithm that only removes a single
inversion at a time will take time at least O(N2)!
• To do better, we need to remove more than one inversion
at a time.
BubbleSort
• Time
– Let N be number of elements
– Number of levels is O(logN)
– At each level, O(N) work
– Total is O(N*logN)
– This is best possible for sorting.
• Space
– At each level, O(N) temporary space
– Space can be freed, but calls to new costly
– Needs O(N) space
– Bad - better to have an in place sort
– Quick Sort (chapter 8) is the sort of choice.
Quicksort: Algorithm
• Worst Case:
– T(N) = worst case sorting time
– T(1) = 1
– if bad pivot, T(N) = T(N-1)+N
– Via Telescope argument (expand and add)
– T(N) = O(N^2)
• Average Case (text argument)
– Assume equally likely subproblem sizes
• Note: chance of picking ith is 1/N
– T(N) average cost to sort
Analysis continued