CS 211: Sorting with Merges

Transcription

CS 211: Sorting with Merges
CS 211: Sorting with Merges
Chris Kauffman
Week 14-2
Front Matter
Deliverables
Topics
I
P7 Now up today, due next
week Mon
I
P7 Overview
I
Review Sorting
I
Lab 14: Review and
Evaluations
I
Merge Sort
I
Attend Lab 14: +1 Day Late
Token (!!)
I
Reading: BJP: Ch 13.4 on
Merge Sort
Schedule
4/27
5/4
Mon
Tue
Wed
Thu
Mon
W14
W15
5/4
5/5
5/6
5/7
5/11
12-1:15pm
3-4:15pm
2-4:30pm
1:30-4:15pm
10:30-1:15pm
Sorting, Comparators
Review
Last day for Sec 2 (Review)
Makeup day for Sec 4 (Review)
Special review office hours
Sec 4 (T/R) Final Exam
Sec 2 (M/W) Final Exam
P7 Quick Overview
key
5341
5346
5318
4100
4451
I
Generic Maps: key/value association
I
I
I
I
value
Chris Kauffman
Mark Snyder
Richard Carver
Main Office
Sean Luke
Any kind of key K, any kind of value V
put(key,val) association into a map
get(key) value associated with given key
contains(key) check if an association exists
AbstractListMM implements MiniMap<K,V>
+-- SimpleListMM : indexOf(key) uses linear search
+-- FastGetListMM : indexOf(key) uses binary search
P7 Tips on Comparable and Comparator
In FastGetListMM, must deal with a Map that has either
Comparable keys or a Comparator
Exercise
Write a function sortEm()
public static <T> void sortEm(ArrayList<T> a,
Comparator<T> optional)
I
Wrapper around Collections.sort(a, cmp) and
Collections.sort(a)
I
If optional is not null, use it to sort the a
I
Otherwise check if a can be caste to
ArrayList<Comparable> and use the other version of
Collections.sort(..)
I
If optional is null and the elements of a are not
Comparable, throw a RuntimeException
This is why you must get 60% on the final exam
I
P5: https:
//www.freelancer.com/jobs/Java/java-project-7467939/
I
P5: https:
//www.freelancer.com/jobs/Java/java-project-7438281/
I
P7: https://www.freelancer.com/jobs/Java/java-proj/
Quick Review
Comparing
I
What’s one way a java class can be made to work with
Arrays.sort(..) and Collections.sort(..)?
I
What’s a different way?
Searching
I
Describe one way to search for data in an array; include any
assumptions necessary for this process to work
I
Describe a fundamentally different way
I
Compare these two approaches according to their worst case
runtime complexity
Quick Review
Sorting
I
Describe how one sorting algorithm works
I
Give give the worst-case runtime complexity of that sorting
algorithm
I
What is the worst-case runtime complexity of the best sorting
algorithms?
I
Given an example of one sorting algorithm that achieves this
complexity
I
What sorting algorithm does Collections.sort(..) use
anyway?
Runtime of Selection sort
public static void selectionSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
int smallest = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[smallest]) {
smallest = j;
}
}
swap(a, i, smallest);
}
}
public static void swap(int[] a, int i, int j) {
int temp = a[i]; a[i] = a[j]; a[j] = temp;
}
I
Each inner loop iteration does a constant amount of work
I
I
Fetch array elements, compare numbers, set variables
Good approximation of runtime: total inner loop iterations
I
For array size 10? size 50? size N?
Asymptotic Speeds To Remember
Input Data
Array of size N
Search
I
Linear search: O(N)
I
Binary search: O(log N)
I
Hash tables: O(1)
Sort
I
Selection sort: O(N 2 )
I
Insertion sort: O(N 2 )
I
Merge sort: O(N log N)
I
Quick sort: O(N log N)
I
Radix sort: O(N) via cheating
Merge Sort
I
Fast sorting algorithm: O(N log N)
I
Exploits recursion
I
Principles are simple but implementation is non-trivial
I
Variants have different properties: out-of place vs in-place
I
Good culmination of CS 211 last two weeks of material
Exercise: Merge
public static void merge(int[] result, int[] a, int[] b)
I
I
I
I
a and b are sorted arrays, may not be same size
Copy elements from a and b into result so that result is
sorted
Assume: result.length = =a.length + b.length
Target Runtime Complexity: O(N) where N is
result.length
Example
int [] a = {1, 6, 7, 9}
int [] b = {0, 2, 3, 4, 8}
int [] result = new int[a.length+b.length];
merge(result, a, b);
print(result)
// [0, 1, 2, 3, 4, 6, 7, 8, 9]
Merge Answers
Textbook
CK preferred
public static
public static
void merge(int[] result,
void merge(int[] result,
int[] a, int[] b) {
int[] a, int[] b) {
int i1 = 0;
int ai=0, bi=0;
int i2 = 0;
for(int ri=0; ri<result.length; ri++){
for(int i = 0; i < result.length; i++){
if(ai >= a.length){
if(i2 >= b.length ||
result[ri] = b[bi];
(i1 < a.length && a[i1] <= b[i2])){
bi++;
result[i] = a[i1];
}
i1++;
else if(bi >= b.length){
}
result[ri] = a[ai];
else {
ai++;
result[i] = b[i2];
}
i2++;
else if(a[ai]<=b[bi]){
}
result[ri] = a[ai];
}
ai++;
}
}
else{
result[ri] = b[bi];
bi++;
}
}
Recursive Application
public static void mergeSort(int[] a) {
if (a.length <= 1) {
return;
}
int[] left = Arrays.copyOfRange(a, 0, a.length/2);
int[] right = Arrays.copyOfRange(a, (a.length/2), a.length);
mergeSort(left);
mergeSort(right);
merge(a, left, right);
}
I
An array if 1 element is sorted
I
If bigger, chop array into two halves
I
Recursively sort left and right halves
I
Merge the sorted results into the original array
Demonstrate
public static void mergeSort(int[] a) {
if (a.length <= 1) {
return;
}
int[] left = Arrays.copyOfRange(a, 0, a.length/2);
int[] right = Arrays.copyOfRange(a, (a.length/2), a.length);
mergeSort(left);
mergeSort(right);
merge(a, left, right);
}
Show Execution for
int [] a = {14, 32, 67, 76, 23, 41, 58, 85};
mergeSort(list);
mergeSortDebug() in CKMergeSort.java is useful to see this
Computational Complexity
I
What is the complexity of mergeSort()
I
Could you prove it?
I
What’s one huge disadvantage of this version of merge sort?
In-Place Merge Sort
I
Making copies of arrays takes time and memory
I
Current version is an out-of-place merge sort
I
For and array of size 1,000,000, need left and right arrays
which total another 1,000,000 units of memory - BAD!
I
Prefer an in-place version to save memory
I
Cost: Implementation complexity
I
Examine: In-place merge sort ported from C++ STL