-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeSort.java
46 lines (41 loc) · 1.13 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
public class MergeSort {
private int[] nums, secondary;
private int num;
public void sort(int[] values) {
this.nums = values;
num = values.length;
this.secondary = new int[num];
mergesort(0, num - 1);
}
private void mergesort(int low, int high) {
if (low < high) {
int middle = low + (high - low) / 2;
mergesort(low, middle); // sort each side
mergesort(middle + 1, high);
merge(low, middle, high); // combine them
}
}
private void merge(int low, int middle, int high) {
for (int i = low; i <= high; i++) {
secondary[i] = nums[i];
}
int i = low;
int j = middle + 1;
int k = low;
while (i <= middle && j <= high) {
if (secondary[i] <= secondary[j]) {
nums[k] = secondary[i];
i++;
} else {
nums[k] = secondary[j];
j++;
}
k++;
}
while (i <= middle) {
nums[k] = secondary[i];
k++;
i++;
}
}
}