-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHybridSort.java
55 lines (47 loc) · 1.41 KB
/
HybridSort.java
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
public class HybridSort {
static final int S = 124; // switch to insertion sort if array size smaller than S
public static void sortIt(int[] arr, int start, int end) {
if (start < end) {
int mid = start + (end - start) / 2;
sortIt(arr, start, mid);
sortIt(arr, mid + 1, end);
merge(arr, start, mid, end);
}
}
public static void merge(int[] arr, int start, int mid, int end) {
if (arr.length <= S) {
InsertionSort.sortIt(arr, start, end);
} else {
int n1 = mid - start + 1;
int n2 = end - mid;
int[] L = new int[n1];
int[] R = new int[n2];
for (int i = 0; i < n1; ++i)
L[i] = arr[start + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[mid + 1 + j];
int i = 0, j = 0;
int k = start;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
}
}