-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm912 Merge Sort Daily.java
39 lines (35 loc) · 1.03 KB
/
m912 Merge Sort Daily.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
class Solution {
public int[] sortArray(int[] nums) {
return mergeSort(nums);
}
private int[] mergeSort(int[] nums) {
if (nums.length <= 1) {
return nums;
}
int[] left = mergeSort(Arrays.copyOfRange(nums, 0, nums.length / 2));
int[] right = mergeSort(Arrays.copyOfRange(nums, nums.length / 2, nums.length));
int leftIndx = 0, rightIndx = 0;
int i = 0;
while (leftIndx < left.length && rightIndx < right.length) {
if (left[leftIndx] < right[rightIndx]) {
nums[i] = left[leftIndx];
++leftIndx;
} else {
nums[i] = right[rightIndx];
++rightIndx;
}
++i;
}
while (leftIndx < left.length) {
nums[i] = left[leftIndx];
++leftIndx;
++i;
}
while (rightIndx < right.length) {
nums[i] = right[rightIndx];
++rightIndx;
++i;
}
return nums;
}
}