-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBottomUpMergeSort.java
More file actions
77 lines (68 loc) · 1.49 KB
/
Copy pathBottomUpMergeSort.java
File metadata and controls
77 lines (68 loc) · 1.49 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
72
73
74
75
76
77
/**
*
* @author KAKANAKOU MIGUEL
*
*/
public final class BottomUpMergeSort {
/**
* Use the merge sort method to sort the given array A
*
* @param A Array of Comparable that contains the object to sort
*/
public static void sort(Comparable[] A) {
if (A == null)
return;
int len = A.length;
int subSize = 1;
int lo, mid, hi;
while (subSize < len ) {
lo = -2 * subSize;
while (true) {
lo = lo + 2 * subSize;
mid = lo + subSize - 1;
hi = mid + subSize;
if (mid >= len)
break;
else if (hi >= len)
hi = len - 1;
merge(A, lo, mid, hi);
}
subSize *= 2;
}
}
private static void merge(Comparable[] A, int lo, int mid, int hi) {
int leftSize = mid - lo + 1;
int rightSize = hi - mid;
Comparable[] left = new Comparable[leftSize];
Comparable[] right = new Comparable[rightSize];
for (int i = 0; i < leftSize; i++)
left[i] = A[lo + i];
for (int i = 0; i < rightSize; i++)
right[i] = A[mid + i + 1];
int leftPt = 0;
int rightPt = 0;
for (int i = lo; i <= hi; i++) {
if (leftPt >= leftSize) {
A[i] = right[rightPt];
rightPt++;
} else if (rightPt >= rightSize) {
A[i] = left[leftPt];
leftPt++;
} else {
if (less(right[rightPt], left[leftPt])) {
A[i] = right[rightPt];
rightPt++;
} else {
A[i] = left[leftPt];
leftPt++;
}
}
}
}
private static boolean less(Comparable a, Comparable b) {
int cmp = a.compareTo(b);
if (cmp < 0)
return true;
return false;
}
}