-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge.java
More file actions
33 lines (27 loc) · 998 Bytes
/
Merge.java
File metadata and controls
33 lines (27 loc) · 998 Bytes
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
public class Merge {
private static Comparable[] aux; // auxiliary arrary for merges
public static void merge( Comparable[] a, int lo, int mid, int hi ) {
// Merge a[lo...mid] with a[mid+1...hi]
int i = lo, j = mid + 1;
for ( int k = lo; k <= hi; k++ ) // Copy a[lo...hi] to aux[lo...hi].
aux[k] = a[k];
for ( int k = lo; k <= hi; k++ ) {
if ( i > mid ) a[k] = aux[ j++ ];
else if ( j > mid ) a[k] = aux[ i++ ];
else if ( less( aux[j], aux[i] ) ) a[k] = aux[ j++ ];
else a[k] = aux[ i++ ];
}
}
public static void sort( Comparable[] a ) {
aux = new Comparable[ a.length ]; // Allocate space just once.
sort( a, 0, a.length - 1 );
}
private static void sort( Comparable[] a, int lo, int hi ) {
// Sort a[lo..hi]
if ( hi <= lo ) return;
int mid = lo + ( hi - lo ) / 2;
sort( a, lo, mid ); // Sort left half.
sort( a, mid + 1, hi ); // Sort right half.
merge( a, lo, mid, hi ); // Merge results ( code on page 271 ).
}
}