File tree Expand file tree Collapse file tree 1 file changed +16
-2
lines changed
src/algorithms/sorting/merge-sort Expand file tree Collapse file tree 1 file changed +16
-2
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Unpacks 'number | undefined' type into 'number'
3
+ *
4
+ * @private
5
+ * @param {number[] } array Numeric array.
6
+ * @returns {number } Shifted array value.
7
+ */
8
+ const shift = ( array ) => array . shift ( ) ?? 0
9
+
1
10
/**
2
11
* Merges two ordered arrays into one ordered array.
12
+ *
13
+ * @private
3
14
* @param {number[] } left One of the arrays to be merged.
4
15
* @param {number[] } right One of the arrays to be merged.
5
16
* @returns {number[] } Merged array.
6
17
*/
7
- const merge = ( left , right ) => {
18
+ const merge = ( left = [ ] , right = [ ] ) => {
19
+ /** @type {number[] } */
8
20
const sorted = [ ]
9
21
10
22
while ( left . length && right . length ) {
11
- sorted . push ( left [ 0 ] <= right [ 0 ] ? left . shift ( ) : right . shift ( ) )
23
+ sorted . push ( left [ 0 ] <= right [ 0 ] ? shift ( left ) : shift ( right ) )
12
24
}
13
25
14
26
return [ ...sorted , ...left , ...right ]
15
27
}
16
28
17
29
/**
18
30
* Sorts a numeric array using the merge sort approach.
31
+ *
19
32
* Time complexity: O(n log n) for best, worst, and average.
20
33
* Space complexity: total O(n) auxiliary O(n).
34
+ *
21
35
* @param {number[] } nums Array to be sorted.
22
36
* @returns {number[] } Sorted array.
23
37
*/
You can’t perform that action at this time.
0 commit comments