SLIDE 1
Week 12 - Friday What did we talk about last time? Sorting - - PowerPoint PPT Presentation
Week 12 - Friday What did we talk about last time? Sorting - - PowerPoint PPT Presentation
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
SLIDE 2
SLIDE 3
SLIDE 4
SLIDE 5
SLIDE 6
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)
SLIDE 7
SLIDE 8
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
SLIDE 9
SLIDE 10
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) { … }
SLIDE 11
SLIDE 12
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(n2)
- Not stable
SLIDE 13
- 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
SLIDE 14
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
SLIDE 15
7 45 54 37 108 7 45 54 37 108 7 45 54 37 108 7 37 45 54 108 7 37 45 54 108 7 37 45 54 108 7 37 45 54 108
SLIDE 16
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(n2) 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
SLIDE 17
SLIDE 18
Lower bound on sorting time Counting sort Radix sort
SLIDE 19
Keep working on Project 4
- Pick teams if you haven't!
Work on Assignment 6
- Due tonight!