-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge.java
More file actions
54 lines (46 loc) · 1.75 KB
/
Merge.java
File metadata and controls
54 lines (46 loc) · 1.75 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
/**
* For additional documentation on this implementation of merge sort,
* see <a href="https://algs4.cs.princeton.edu/22mergesort">Section 2.2</a>
* of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*/
public class Merge {
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static final void sort(int[] a) {
int[] aux = new int[a.length];
sort(a, aux, 0, a.length-1);
assert Insertion.isSorted(a);
}
// mergesort a[lo..hi] using auxiliary array aux[lo..hi]
private static final void sort(int[] a, int[] aux, int lo, int hi) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, aux, lo, mid);
sort(a, aux, mid + 1, hi);
merge(a, aux, lo, mid, hi);
}
// stably merge a[lo..mid] with a[mid+1..hi] using aux[lo..hi]
private static final void merge(int[] a, int[] aux, int lo, int mid, int hi) {
// precondition: a[lo..mid] and a[mid+1..hi] are sorted subarrays
assert Insertion.isSorted(a, lo, mid);
assert Insertion.isSorted(a, mid+1, hi);
// copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
// merge back to a[]
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = aux[j++];
else if (j > hi) a[k] = aux[i++];
else if (aux[j] < aux[i]) a[k] = aux[j++];
else a[k] = aux[i++];
}
// postcondition: a[lo..hi] is sorted
assert Insertion.isSorted(a, lo, hi);
}
// This class should not be instantiated.
private Merge() { }
}