|
1 |
| -function findMinValue(arr){ |
| 1 | +function findMinValue(arr) { |
2 | 2 | let min = arr[0];
|
3 |
| - for (i = 0; i < arr.length; i++){ |
4 |
| - if (arr[i] < min){ |
| 3 | + for (let i = 0; i < arr.length; i++) { |
| 4 | + if (arr[i] < min) { |
5 | 5 | min = arr[i];
|
6 | 6 | }
|
7 | 7 | }
|
8 | 8 | return min;
|
9 | 9 | }
|
10 | 10 |
|
11 |
| -//Create a function with an array of numbers as its parameter. This function will return a new array with the numbers sorted from least to greatest value. |
| 11 | +function sortArray(arr) { |
| 12 | + let sortedArray = []; |
12 | 13 |
|
13 |
| -/*Within the function: |
14 |
| -1) Define a new, empty array to hold the final sorted numbers. |
15 |
| -2) Use the findMinValue function to find the minimum value in the old array. |
16 |
| -3) Add the minimum value to the new array, and remove the minimum value from the old array. |
17 |
| -4) Repeat parts b & c until the old array is empty. |
18 |
| -5) Return the new sorted array. |
19 |
| -6) Be sure to print the results in order to verify your code.*/ |
20 |
| - |
21 |
| -//Your function here... |
| 14 | + while (arr.length > 0) { |
| 15 | + let minValue = findMinValue(arr); |
| 16 | + sortedArray.push(minValue); |
| 17 | + arr.splice(arr.indexOf(minValue), 1); |
| 18 | + } |
22 | 19 |
|
23 |
| -/* BONUS MISSION: Refactor your sorting function to use recursion below: |
24 |
| - */ |
| 20 | + return sortedArray; |
| 21 | +} |
25 | 22 |
|
26 |
| -//Sample arrays for testing: |
| 23 | +// Sample arrays for testing: |
27 | 24 | let nums1 = [5, 10, 2, 42];
|
28 | 25 | let nums2 = [-2, 0, -10, -44, 5, 3, 0, 3];
|
29 | 26 | let nums3 = [200, 5, 4, 10, 8, 5, -3.3, 4.4, 0];
|
| 27 | + |
| 28 | +console.log("Sorted nums1:", sortArray(nums1)); // [2, 5, 10, 42] |
| 29 | +console.log("Sorted nums2:", sortArray(nums2)); // [-44, -10, -2, 0, 0, 3, 3, 5] |
| 30 | +console.log("Sorted nums3:", sortArray(nums3)); // [-3.3, 0, 4.4, 4, 5, 5, 8, 10, 200] |
| 31 | + |
| 32 | + |
| 33 | + |
| 34 | +function findMinValue(arr) { |
| 35 | + let min = arr[0]; |
| 36 | + for (let i = 0; i < arr.length; i++) { |
| 37 | + if (arr[i] < min) { |
| 38 | + min = arr[i]; |
| 39 | + } |
| 40 | + } |
| 41 | + return min; |
| 42 | +} |
| 43 | + |
| 44 | +function sortArray(arr) { |
| 45 | + if (arr.length === 0) { |
| 46 | + return []; |
| 47 | + } |
| 48 | + |
| 49 | + let minValue = findMinValue(arr); |
| 50 | + arr.splice(arr.indexOf(minValue), 1); |
| 51 | + |
| 52 | + return [minValue].concat(sortArray(arr)); |
| 53 | +} |
| 54 | + |
| 55 | +console.log("Sorted nums1:", sortArray(nums1)); // [2, 5, 10, 42] |
| 56 | +console.log("Sorted nums2:", sortArray(nums2)); // [-44, -10, -2, 0, 0, 3, 3, 5] |
| 57 | +console.log("Sorted nums3:", sortArray(nums3)); // [-3.3, 0, 4.4, 4, 5, 5, 8, 10, 200] |
0 commit comments