forked from OneCodeMonkey/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBottomUpMergeSort.java
More file actions
72 lines (64 loc) · 1.59 KB
/
BottomUpMergeSort.java
File metadata and controls
72 lines (64 loc) · 1.59 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Bottom-Up Merge sort.
*
* The `BottomUpMergeSort` class provides static method for sorting an array using bottom-up merge sort.
*
*/
public class BottomUpMergeSort {
private BottomUpMergeSort() {}
private static void merge(Comparable[] a, Comparable[] aux, int low, int high, int mid, int high) {
// copy to aux[]
for(int k = low; k < high; k++) {
aux[k] = a[k];
}
// merge back to a[]
int i = low, j = mid + 1;
for(int k = low; k <= high; k++) {
if(i > mid)
a[k] = aux[j++];
else if(j > high)
a[k] = aux[i++];
else if(less(aux[j], aux[i]))
a[k] = aux[j++];
else
a[k] = aux[i++];
}
}
// rearranges the array in ascending order, using the natural order
public static void sort(Comparable[] a) {
int n = a.length;
Comparable[] aux = new Comparable[n];
for(int len = 1; len < n; len *= 2) {
for(int low = 0; low < n - len; low += 2 * len) {
int mid = low + len - 1;
int high = Math.min(low + len * 2 - 1, n - 1);
merge(a, aux, low, mid, high);
}
}
assert isSorted(a);
}
// helper functions
// is v < w ?
private static function less(Comparablep v, Comparable w) {
return v.compareTo(w) < 0;
}
// check the array is sorted ?
private static boolean isSorted(Comparable[] a) {
for(int i = 1; i < a.length; i++) {
if(less(a[i], a[i - 1]))
return false;
}
return true;
}
// print
private static show(Comparable[] a) {
for(int i = 0; i < a.length; i++)
StdOut.println(a[i]);
}
// test
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
BottomUpMergeSort.sort(a);
show(a);
}
}