-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathMergeSort.java
119 lines (98 loc) · 2.7 KB
/
MergeSort.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/**
* MergeSort: It divides input array in two halves, calls itself for the two
* halves and then merges the two sorted halves.
*
* Time Complexity: O(nLogn) in all 3 cases (worst, average and best).
* Space Complexity: O(n).
*
*/
import java.util.Arrays;
public class MergeSort {
public static void sort(int[] arr) {
mergeSort(arr, 0, arr.length-1);
// int[] helper = new int[arr.length];
// mergeSort(arr, helper, 0, arr.length-1);
}
private static void mergeSort(int[] arr, int l, int r) {
if (l >= r) return;
int m = (l+r)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
private static void merge(int[] arr, int l, int m, int r) {
int len1 = m - l + 1;
int len2 = r - m;
int L[] = new int [len1];
int R[] = new int [len2];
for (int i=0; i < len1; i++)
L[i] = arr[l + i];
for (int j=0; j < len2; j++)
R[j] = arr[m + 1 + j];
int i = 0;
int j = 0;
int k = l;
while (i < len1 && j < len2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < len1) {
arr[k] = L[i];
i++;
k++;
}
while (j < len2) {
arr[k] = R[j];
j++;
k++;
}
}
//
private static void mergeSort(int[] arr, int[] helper, int l, int r) {
if (l >= r) return;
int m = (l+r)/2;
mergeSort(arr, helper, l, m);
mergeSort(arr, helper, m+1, r);
merge(arr, helper, l, m, r);
}
private static void merge(int[] arr, int[] helper, int l, int m, int r) {
for (int i = l; i <= r; i++) {
helper[i] = arr[i];
}
int i = l;
int j = m + 1;
int k = l;
while (i <= m && j <= r) {
if (helper[i] <= helper[j]) {
arr[k] = helper[i];
i++;
} else {
arr[k] = helper[j];
j++;
}
k++;
}
while (i <= m) {
arr[k] = helper[i];
k++;
i++;
}
}
public static void main(String[] args) {
int[] arr1 = {10, 3, 7, 5, 20, 15, 1};
MergeSort.sort(arr1);
System.out.println(Arrays.toString(arr1));
int[] arr2 = {};
MergeSort.sort(arr2);
System.out.println(Arrays.toString(arr2));
int[] arr3 = {10};
MergeSort.sort(arr3);
System.out.println(Arrays.toString(arr3));
}
}