-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMergeSort.java
52 lines (43 loc) · 1.35 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
package algorithms.sort;
/*
* Stable sort
* time: O(n log n) log linear complexity
* not an in-place Algorithm
*/
import java.util.Arrays;
public class MergeSort {
public static void merge(int[] leftArray, int[] rightArray, int[] arr, int leftSize, int rightSize) {
int tempIndex = 0, i = 0, j = 0;
while (i < leftSize && j < rightSize) {
if (leftArray[i] < rightArray[j]) {
arr[tempIndex++] = leftArray[i++];
} else {
arr[tempIndex++] = rightArray[j++];
}
}
while (i < leftSize) {
arr[tempIndex++] = leftArray[i++];
}
while (j < rightSize) {
arr[tempIndex++] = rightArray[j++];
}
}
public static void mergeSort(int[] arr, int len) {
if (len < 2) {
return;
}
int mid = len / 2;
int[] leftArray = Arrays.copyOfRange(arr, 0, mid);
int[] rightArray = Arrays.copyOfRange(arr, mid, len);
mergeSort(leftArray, mid);
mergeSort(rightArray, len - mid);
merge(leftArray, rightArray, arr, mid, len - mid);
}
public static void main(String[] args) {
int[] arr = {23, 43, 43, 21, 2, 4, 77, 9, 0, 788, 7};
mergeSort(arr, arr.length);
for (int item : arr) {
System.out.println(item);
}
}
}