Skip to content
Snippets Groups Projects
Commit e491c5d6 authored by Martin Vatshelle's avatar Martin Vatshelle
Browse files

Code after lecture

parent 0116e6ce
No related branches found
No related tags found
No related merge requests found
package sorting;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MergeSort implements Sorter{
@Override
public <T extends Comparable<? super T>> void sort(List<T> list) {
if(list.size()<=2) { //O(1)
if(list.size()==2) {
if(list.get(0).compareTo(list.get(1))>0) {
Collections.swap(list, 0, 1);
}
}
return;
}
//divide
int mid = list.size()/2; //O(1)
ArrayList<T> first = new ArrayList<T>(list.subList(0, mid)); //O(n)
ArrayList<T> last = new ArrayList<T>(list.subList(mid, list.size())); //O(n)
//recurse
sort(first);
sort(last);
//conquer
int i=0;
int j=0;
int index=0;
while(i<first.size() && j<last.size()) {//n iterations O(1)
if(first.get(i).compareTo(last.get(j))<0) {
list.set(index, first.get(i));
i++;
}
else {
list.set(index, last.get(j));
j++;
}
index++;
}
while(i<first.size()) {
list.set(index, first.get(i));
i++;
index++;
}
while(j<last.size()) {
list.set(index, last.get(j));
j++;
index++;
}
}
}
......@@ -25,9 +25,9 @@ class SorterTest {
toTest = new ArrayList<Sorter>();
toTest.add(new JavaSort());
//toTest.add(new SelectionSort());
toTest.add(new InsertionSort());
//toTest.add(new InsertionSort());
toTest.add(new QuickSort());
//toTest.add(new MergeSort());
toTest.add(new MergeSort());
inputStrings = RandomListGenerator.generateStrings(1000000);
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment