Write a recursive function called `sort` that takes an array of integers, `nums` and returns an array containing those integers sorted from least to greatest. Your function should accept a default argument called `sorted` which holds the currently sorted elements. Each recursive step should add the
(nums, sorted = [])
| 22 | ***********************************************************************/ |
| 23 | |
| 24 | function sort(nums, sorted = []) { |
| 25 | //!!START |
| 26 | // Base case: all numbers are in the sorted array |
| 27 | if (nums.length == 0) { |
| 28 | return sorted; |
| 29 | } |
| 30 | |
| 31 | // Find the smallest number in the nums array |
| 32 | let minIndex = 0; |
| 33 | for (let i = 1 ; i < nums.length ; i++) { |
| 34 | if (nums[i] < nums[minIndex]) { |
| 35 | minIndex = i; |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | // Add the smallest number to the end of the sorted array |
| 40 | sorted.push(nums[minIndex]); |
| 41 | |
| 42 | // Remove the smallest number from the nums array |
| 43 | nums.splice(minIndex, 1); |
| 44 | |
| 45 | // Recursively call sort with the new array |
| 46 | return sort(nums, sorted); |
| 47 | //!!END |
| 48 | } |
| 49 | |
| 50 | /**************DO NOT MODIFY ANYTHING UNDER THIS LINE*****************/ |
| 51 | module.exports = sort; |