-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMergeSort.java
70 lines (56 loc) · 1.74 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
package Incognito;
import java.util.ArrayList;
/**
*
* @author adenugad
*/
/** Inspiration from
* http://www.vogella.com/tutorials/JavaAlgorithmsMergesort/article.html
* @author adenugad
*/
public class MergeSort {
private static ArrayList<Vertex> vertexes = new ArrayList<>();
private static ArrayList<Vertex> tempVertexes = new ArrayList<>();
public static ArrayList<Vertex> sort(ArrayList<Vertex> vS){
if(vS.isEmpty()){
return vS;
}
//System.out.println( "list size: "+vS.size());
vertexes = vS;
//System.out.println( "list size: "+vertexes.size());
mergesort(0, vertexes.size()-1);
return vertexes;
}
public static void mergesort(int low, int high){
if(low < high){
int middle = (low + high)/2;
mergesort(low, middle);
mergesort(middle + 1, high);
merge(low, middle, high);
}
}
public static void merge(int low, int middle, int high){
for(int i = 0; i < vertexes.size(); i++){
tempVertexes.add(i, vertexes.get(i).copy());
}
int i = low;
int j = middle + 1;
int k = low;
while(i <= middle && j <= high){
if(tempVertexes.get(i).getVertexHeight() <= tempVertexes.get(j).getVertexHeight()){
vertexes.set(k, tempVertexes.get(i));
i++;
}
else{
vertexes.set(k, tempVertexes.get(j));
j++;
}
k++;
}
while(i <= middle){
vertexes.set(k, tempVertexes.get(i));
i++;
k++;
}
}
}