MCPcopy Create free account
hub / github.com/appacademy/Module-1-Resources / sort

Function sort

w3/d3/solutions/recursion-pt4/problems/13-sort.js:24–48  ·  view source on GitHub ↗

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 = [])

Source from the content-addressed store, hash-verified

22***********************************************************************/
23
24function 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*****************/
51module.exports = sort;

Callers 1

13-sort-spec.jsFile · 0.50

Calls

no outgoing calls

Tested by

no test coverage detected