-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeSort.java
99 lines (81 loc) · 2.63 KB
/
MergeSort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/***
* MergeSort Algorithm is implemented thanks to uni lecture materials
* and the following tutorial:
* https://www.codexpedia.com/java/java-merge-sort-implementation/
*/
import java.util.ArrayList;
public class MergeSort implements SortingAlgorithm{
long start,end;
@Override
public ArrayList<Integer> sort(ArrayList<Integer> input) {
start = System.nanoTime();
/**
* Find the middle of the array and split its contents
* into two different arrays
* @param left
* @param right
* */
int middleIndex = (int) (double)input.size()/2;
ArrayList<Integer> left = new ArrayList<>();
ArrayList<Integer> right = new ArrayList<>();
if (input.size() == 1){
end = System.nanoTime();
return input;
} else {
for (int i = 0; i < middleIndex; i++){
left.add(input.get(i));
}
for (int i = middleIndex ; i < input.size(); i++){
right.add(input.get(i));
}
/** Recursively sort both partitions & merge the result together **/
left = sort(left);
right = sort(right);
return merge(left,right,input);
}
}
@Override
public long executionTime() {
return end-start;
}
public ArrayList<Integer> merge(ArrayList<Integer> left, ArrayList<Integer> right, ArrayList<Integer> input){
int leftIndex = 0;
int rightIndex = 0;
int inputIndex = 0;
int restIndex;
ArrayList<Integer> rest;
/** Select the smallest of Integers in either
* partition of the sorted input to add to
* @param input
*/
while (leftIndex < left.size() && rightIndex < right.size()){
if ( (left.get(leftIndex).compareTo(right.get(rightIndex)) < 0)){
input.set(inputIndex, left.get(leftIndex));
leftIndex++;
} else {
input.set(inputIndex, right.get(rightIndex));
rightIndex++;
}
inputIndex++;
}
/** Select the rest of elements (if any) to add to
* @param input
*/
if(leftIndex >= left.size()){
rest = right;
restIndex = rightIndex;
} else {
rest = left;
restIndex = leftIndex;
}
for (int i = restIndex; i<rest.size(); i++){
input.set(inputIndex, rest.get(i));
inputIndex++;
}
return input;
}
@Override
public String getAlgorithmName() {
return "Merge Sort";
}
}