Skip to content

Commit 5902fc8

Browse files
authored
Update 0912-sort-an-array.js
Created helper functions outside of the main function.
1 parent 671fffd commit 5902fc8

File tree

1 file changed

+35
-36
lines changed

1 file changed

+35
-36
lines changed

javascript/0912-sort-an-array.js

+35-36
Original file line numberDiff line numberDiff line change
@@ -5,50 +5,49 @@
55
* @param {number[]} nums
66
* @return {number[]}
77
*/
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;
915

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+
}
1721

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;
2829

29-
while(p1 < arr1.length) {
30+
while(p1 < arr1.length && p2 < arr2.length) {
31+
if(arr1[p1] < arr2[p2]) {
3032
nums[gp] = arr1[p1];
3133
p1++;
32-
gp++;
33-
}
34-
35-
while(p2 < arr2.length) {
34+
} else {
3635
nums[gp] = arr2[p2];
3736
p2++;
38-
gp++;
3937
}
40-
return nums;
41-
}
42-
43-
const mergeSort = (left, right) => {
38+
gp++;
39+
}
4440

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++;
5145
}
5246

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

Comments
 (0)