-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
47 lines (44 loc) · 1.19 KB
/
MergeSort.java
File metadata and controls
47 lines (44 loc) · 1.19 KB
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
public class MergeSort {
public static void sort (int [] a) {
int [] aux = new int[a.length];
sort(a, aux, 0, a.length);
}
private static void sort(int [] a, int [] aux, int lo, int hi) {
if (hi - lo <= 1) return;
int mid = lo + (hi - lo) / 2;
sort(a, aux, lo, mid);
sort(a, aux, mid, hi);
merge(a, aux, lo, mid, hi);
}
private static void merge(int [] a, int [] aux, int lo, int mid, int hi) {
int i = lo;
int j = mid;
for (int k = lo; k < hi; k++) {
if (i == mid) {
aux[k] = a[j];
j++;
}
if (j == hi) {
aux[k] = a[i];
i++;
}
if (a[j] < (a[i])) {
aux[k] = a[j];
j++;
} else {
aux[k] = a[i];
i++;
}
for (int l = lo; l < hi; l++) {
a[k] = aux[k];
}
}
}
public static void main(String[] args) {
int [] a = StdIn.readAllInts();
sort(a);
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i] + " ");
}
}
}