-
Notifications
You must be signed in to change notification settings - Fork 0
/
SortingWithoutBuiltIn.java
43 lines (37 loc) · 1.18 KB
/
SortingWithoutBuiltIn.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
class SortingWithoutBuiltIn {
public int[] sortArray(int[] nums) {
mergeSort(nums, 0, nums.length - 1);
return nums;
}
private void mergeSort(int[] array, int low, int high) {
if (low >= high) {
return;
}
int mid = low + (high - low) / 2;
mergeSort(array, low, mid);
mergeSort(array, mid + 1, high);
merge(array, low, mid, high);
}
private void merge(int[] array, int low, int mid, int high) {
int n1 = mid - low + 1;
int n2 = high - mid;
int[] leftPart = new int[n1];
int[] rightPart = new int[n2];
System.arraycopy(array, low, leftPart, 0, n1);
System.arraycopy(array, mid + 1, rightPart, 0, n2);
int p1 = 0, p2 = 0, writeInd = low;
while (p1 < n1 && p2 < n2) {
if (leftPart[p1] <= rightPart[p2]) {
array[writeInd++] = leftPart[p1++];
} else {
array[writeInd++] = rightPart[p2++];
}
}
while (p1 < n1) {
array[writeInd++] = leftPart[p1++];
}
while (p2 < n2) {
array[writeInd++] = rightPart[p2++];
}
}
}