|
5 | 5 | * @param {number[]} nums
|
6 | 6 | * @return {number[]}
|
7 | 7 | */
|
8 |
| -var sortArray = function(nums) { |
| 8 | +const sortArray = function(nums) { |
| 9 | + return mergeSort(0, nums.length - 1, nums); |
| 10 | +}; |
| 11 | + |
| 12 | +const mergeSort = (left, right, nums) => { |
| 13 | + |
| 14 | + if(left === right) return nums; |
9 | 15 |
|
10 |
| - const merge = (left, mid, right) => { |
11 |
| - const arr1 = nums.slice(left, mid+1); |
12 |
| - const arr2 = nums.slice(mid+1, right + 1); |
13 |
| - |
14 |
| - let p1 = 0; |
15 |
| - let p2 = 0; |
16 |
| - let gp = left; |
| 16 | + const mid = Math.floor((left+right)/2); |
| 17 | + mergeSort(left, mid, nums); |
| 18 | + mergeSort(mid+1, right, nums); |
| 19 | + return merge(left, right, mid, nums); |
| 20 | +} |
17 | 21 |
|
18 |
| - while(p1 < arr1.length && p2 < arr2.length) { |
19 |
| - if(arr1[p1] < arr2[p2]) { |
20 |
| - nums[gp] = arr1[p1]; |
21 |
| - p1++; |
22 |
| - } else { |
23 |
| - nums[gp] = arr2[p2]; |
24 |
| - p2++; |
25 |
| - } |
26 |
| - gp++; |
27 |
| - } |
| 22 | +const merge = (left, right, mid, nums) => { |
| 23 | + const arr1 = nums.slice(left, mid+1); |
| 24 | + const arr2 = nums.slice(mid+1, right + 1); |
| 25 | + |
| 26 | + let p1 = 0; |
| 27 | + let p2 = 0; |
| 28 | + let gp = left; |
28 | 29 |
|
29 |
| - while(p1 < arr1.length) { |
| 30 | + while(p1 < arr1.length && p2 < arr2.length) { |
| 31 | + if(arr1[p1] < arr2[p2]) { |
30 | 32 | nums[gp] = arr1[p1];
|
31 | 33 | p1++;
|
32 |
| - gp++; |
33 |
| - } |
34 |
| - |
35 |
| - while(p2 < arr2.length) { |
| 34 | + } else { |
36 | 35 | nums[gp] = arr2[p2];
|
37 | 36 | p2++;
|
38 |
| - gp++; |
39 | 37 | }
|
40 |
| - return nums; |
41 |
| - } |
42 |
| - |
43 |
| - const mergeSort = (left, right) => { |
| 38 | + gp++; |
| 39 | + } |
44 | 40 |
|
45 |
| - if(left === right) return nums; |
46 |
| - |
47 |
| - const mid = Math.floor((left+right)/2); |
48 |
| - mergeSort(left, mid); |
49 |
| - mergeSort(mid+1, right); |
50 |
| - return merge(left, mid, right); |
| 41 | + while(p1 < arr1.length) { |
| 42 | + nums[gp] = arr1[p1]; |
| 43 | + p1++; |
| 44 | + gp++; |
51 | 45 | }
|
52 | 46 |
|
53 |
| - return mergeSort(0, nums.length - 1); |
54 |
| -}; |
| 47 | + while(p2 < arr2.length) { |
| 48 | + nums[gp] = arr2[p2]; |
| 49 | + p2++; |
| 50 | + gp++; |
| 51 | + } |
| 52 | + return nums; |
| 53 | +} |
0 commit comments