forked from Ayush7-BYTE/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSortInPlace.java
58 lines (46 loc) · 1.23 KB
/
MergeSortInPlace.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
import java.util.Arrays;
public class MergeSortInPlace {
public static void main(String[] args) {
int[] arr = { 4, 6, 7, 4, 3, 1, 1 };
MergeSortInPla(arr, 0, arr.length);
System.out.println(Arrays.toString(arr));
}
private static void MergeSortInPla(int[] arr, int s, int e) {
if (e - s == 1)
return;
int m = s + (e - s) / 2;
MergeSortInPla(arr, s, m);
MergeSortInPla(arr, m, e);
Merge(arr, s, m, e);
}
private static void Merge(int[] arr, int s, int m, int e) {
int[] ans = new int[e - s];
int i = s;
int j = m;
int index = 0;
while (i < m && j < e) {
if (arr[i] < arr[j]) {
ans[index] = arr[i];
i++;
index++;
} else {
ans[index] = arr[j];
j++;
index++;
}
}
while (i < m) {
ans[index] = arr[i];
i++;
index++;
}
while (j < e) {
ans[index] = arr[j];
j++;
index++;
}
for (int a = 0; a < ans.length; a++) {
arr[s + a] = ans[a];
}
}
}