Skip to content

Commit 6ac2538

Browse files
committed
Create 912.排序数组.js
1 parent 5ac8b8b commit 6ac2538

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

912.排序数组.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[]}
4+
*/
5+
var sortArray = function(nums) {
6+
function mergeSort(i, j) {
7+
if (i === j) {
8+
return [nums[i]];
9+
}
10+
const mid = (i + j) >> 1;
11+
const left = mergeSort(i, mid);
12+
const right = mergeSort(mid + 1, j);
13+
const result = [];
14+
let a = 0;
15+
let b = 0;
16+
while (a < left.length && b < right.length) {
17+
if (left[a] <= right[b]) {
18+
result.push(left[a]);
19+
a++;
20+
} else {
21+
result.push(right[b]);
22+
b++;
23+
}
24+
}
25+
while (a < left.length) {
26+
result.push(left[a]);
27+
a++;
28+
}
29+
while (b < right.length) {
30+
result.push(right[b]);
31+
b++;
32+
}
33+
return result;
34+
}
35+
return mergeSort(0, nums.length - 1);
36+
};

0 commit comments

Comments
 (0)