Week 12 - Friday
What did we talk about last time? Sorting Insertion sort Started merge sort
Lab hours Wednesdays at 5 p.m. in The Point 113 Saturdays at noon in The Point 113 CS Club Tuesdays at 5 p.m. in The Point 113 (or next door in The Point 112)
Take a list of numbers, and divide it in half, then, recursively: Merge sort each half After each half has been sorted, merge them together in order
public static void mergeSort(double[] values) { double[] scratch = new double[values.length]; mergeSort(values, scratch, 0, values.length); } private static void mergeSort(double[] values, double[] scratch, int start, int end) { … } private static void merge(double[] values, double[] scratch, int start, int mid, int end) { … }
Pros: Best and average case running time of O( n log n ) Very simple implementation In-place Ideal for arrays Cons: Worst case running time of O( n 2 ) Not stable
1. Pick a pivot 2. Partition the array into a left half smaller than the pivot and a right half bigger than the pivot 3. Recursively, quicksort the left half 4. Recursively quicksort the right half
Input: array , index , left , right Set pivot to be array [ index ] Swap array [ index ] with array [ right ] Set index to left For i from left up to right – 1 If array [ i ] ≤ pivot ▪ Swap array [ i ] with array [ index ] ▪ index ++ Swap array [ index ] with array [ right ] Return index //so that we know where pivot is
7 0 0 0 0 0 0 45 7 7 7 7 7 7 0 45 45 37 37 37 37 54 54 54 45 45 45 45 37 37 37 54 54 54 54 108 108 108 108 108 108 108
Everything comes down to picking the right pivot If you could get the median every time, it would be great A common choice is the first element in the range as the pivot Gives O( n 2 ) performance if the list is sorted (or reverse sorted) Why? Another implementation is to pick a random location Another well-studied approach is to pick three random locations and take the median of those three An algorithm exists that can find the median in linear time, but its constant is HUGE
Lower bound on sorting time Counting sort Radix sort
Keep working on Project 4 Pick teams if you haven't! Work on Assignment 6 Due tonight! Read Section 5.3
Recommend
More recommend