forked from ossamamehmood/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInplaceMergeSort.java
62 lines (48 loc) · 1.29 KB
/
InplaceMergeSort.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
56
57
58
59
60
61
62
import java.util.Arrays;
public class MergeSortInPlace {
public static void main(String[] args) {
int[] arr = {5, 4, 3, 2, 1};
mergeSortInPlace(arr, 0, arr.length);
System.out.println(Arrays.toString(arr));
}
static void mergeSortInPlace(int[] arr, int s, int e) {
if (e - s == 1) {
return;
}
int mid = (s + e) / 2;
mergeSortInPlace(arr, s, mid);
mergeSortInPlace(arr, mid, e);
mergeInPlace(arr, s, mid, e);
}
private static void mergeInPlace(int[] arr, int s, int m, int e) {
int[] mix = new int[e - s];
int i = s;
int j = m;
int k = 0;
while (i < m && j < e) {
if (arr[i] < arr[j]) {
mix[k] = arr[i];
i++;
} else {
mix[k] = arr[j];
j++;
}
k++;
}
// it may be possible that one of the arrays is not complete
// copy the remaining elements
while (i < m) {
mix[k] = arr[i];
i++;
k++;
}
while (j < e) {
mix[k] = arr[j];
j++;
k++;
}
for (int l = 0; l < mix.length; l++) {
arr[s+l] = mix[l];
}
}
}