-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSortOpt.java
More file actions
62 lines (55 loc) · 1.75 KB
/
mergeSortOpt.java
File metadata and controls
62 lines (55 loc) · 1.75 KB
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 MergeSortOpt {
public int[] mergeSort(int[] array) {
if (array == null || array.length == 0) {
return array;
}
int[] helper = new int[array.length];
mergeSortHelper(array, helper, 0, array.length - 1);
return array;
}
private void mergeSortHelper(int[] array, int[] helper, int low, int high) {
if (low >= high) {
return;
}
int mid = low + (high - low) / 2;
mergeSortHelper(array, helper, low, mid);
mergeSortHelper(array, helper, mid + 1, high);
merge(array, helper, low, mid, high);
}
private void merge(int[] array, int[] helper, int low, int mid, int high) {
for (int i = low; i <= high; i++) {
helper[i] = array[i];
}
int leftId = low;
int rightId = mid + 1;
while (leftId <= mid && rightId <= high) {
if (helper[leftId] <= helper[rightId]) {
array[low++] = helper[leftId++];
} else {
array[low++] = helper[rightId++];
}
}
while (leftId <= mid) {
array[low++] = helper[leftId++];
}
}
public static void main(String[] args) {
MergeSortOpt solution = new MergeSortOpt();
int[] array = null;
array = solution.mergeSort(array);
System.out.println(Arrays.toString(array));
array = new int[0];
array = solution.mergeSort(array);
System.out.println(Arrays.toString(array));
array = new int[]{1,2,3,4};
array = solution.mergeSort(array);
System.out.println(Arrays.toString(array));
array = new int[]{4,3,2,1};
array = solution.mergeSort(array);
System.out.println(Arrays.toString(array));
array = new int[]{2,4,1,6,3};
array = solution.mergeSort(array);
System.out.println(Arrays.toString(array));
}
}