


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



Lecture 12 CS211 – Summer 2008
2
y Many people sort cards this way y Invariant: everything to left of i is already sorted y Works especially well when input is nearly sorted
y Worst-case is O(n^2 ) Consider reverse-sorted input y Best-case is O(n) Consider sorted input y Expected case is O(n^2 ) Expected number of inversions is n(n–1)/
//sort a[], an array of int for (int i = 1; i < a.length; i++) { int temp = a[i]; int k; for (k = i; 0 < k && temp < a[k–1]; k––) a[k] = a[k–1]; a[k] = temp; }
3
y To sort an array of size n: Examine a[0] to a[n–1] ; find the smallest one and swap it with a[0] Examine a[1] to a[n–1] ; find the smallest one and swap it with a[1] In general, in step i, examine a[i] to a[n–1] ; find the smallest one and swap it with a[i]
y This is the other common way for people to sort cards
y Runtime Worst-case O(n 2 ) Best-case O(n 2 ) Expected-case O(n 2 )
4
Break the problem into smaller subproblems, Solve the subproblems separately, and then Assemble a final solution
Caveat: It won’t help unless the partitioning and assembly processes are inexpensive
y Quintessential divide-and-conquer algorithm
y Divide array into equal parts, sort each part, then merge
y Questions:
Q1: How do we divide array into two equal parts? A1: Find middle index: a.length/
Q2: How do we sort the parts? A2: call MergeSort recursively!
Q3: How do we merge the sorted subarrays? A3: We have to write some (easy) code
y Create an array C of size = size of A + size of B y Keep three indices: i into A j into B k into C y Initialize all three indices to 0 (start of each array) y Compare element A[i] with B[j] , and move the smaller element into C[k] y Increment i or j , whichever one we took, and k y When either A or B becomes empty, copy remaining elements from the other array ( B or A , respectively) into C
7
1 3 4 4 6 7
1 3 4 6 8
k 4 7 7 8 9
i
j
8
y Outline (detailed code on the website) Split array into two halves Recursively sort each half Merge the two halves
y Merge = combine two sorted arrays to make a single sorted array Rule: always choose the smallest item Time: O(n) where n is the combined size of the two arrays
y Runtime recurrence Let T(n) be the time to sort an array of size n T(n) = 2T(n/2) + O(n) T(1) = 1
y Can show by induction that T(n) is O(n log n)
y Alternately, can see that T(n) is O(n log n) by looking at tree of recursive calls
9
Much faster than O(n^2 )
Need extra storage for temporary arrays In practice, this can be a disadvantage, even though MergeSort is asymptotically optimal for sorting Can do MergeSort in place, but this is very tricky (and it slows down the algorithm significantly)
Yes: QuickSort
10
Given an array A to sort, choose a pivot value p Partition A into two subarrays, AX and AY AX contains only elements ≤ p AY contains only elements ≥ p Sort subarrays AX and AY separately Concatenate (not merge!) sorted AX and AY to get sorted A Concatenation is easier than merging – O(1)
20 31 24 19 45 56 4 65 5 72 14 99
pivot partition
(^5 ) 14
4
31 72
56
(^65 )
24
99
4 5 14 19 20 24 31 45 56 65 72 99
QuickSort QuickSort
4 5 14 19 20 24 31 45 56 65 72 99
concatenate
y Key problems How should we choose a pivot? How do we partition an array in place?
y Partitioning in place Can be done in O(n) time (next slide)
y Choosing a pivot Ideal pivot is the median, since this splits array in half Computing the median of an unsorted array is O(n), but algorithm is quite complicated Popular heuristics: Use first value in array (usually not a good choice) Use middle value in array Use median of first, last, and middle values in array Choose a random element
19
y Comparison-based algorithms make decisions based on comparison of data elements
y This gives a comparison tree y If the algorithm fails to terminate for some input, then the comparison tree is infinite
y The height of the comparison tree represents the worst-case number of comparisons for that algorithm
y Can show that any correct comparison-based algorithm must make at least n log n comparisons in the worst case
a[i] < a[j] no yes
20
y Say we have a correct comparison-based algorithm
y Suppose we want to sort the elements in an array B[]
y Assume the elements of B[] are distinct
y Any permutation of the elements is initially possible
y When done, B[] is sorted
y But the algorithm could not have taken the same path in the comparison tree on different input permutations
y How many input permutations are possible? n! ~ 2n log n
y For a comparison-based sorting algorithm to be correct, it must have at least that many leaves in its comparison tree
y to have at least n! ~ 2n log n^ leaves, it must have height at least n log n (since it is only binary branching, the number of nodes at most doubles at every depth)
y therefore its longest path must be of length at least n log n, and that it its worst-case running time