Make sure to label each step from 1 to 11.
Take note of the loops and recursive calls within the code. It's recommended to familiarize yourself with recursion before delving into this code for a better understanding.
An additional note: I have included logging for each instance the minIndex
function is invoked, displaying the current indices and values being compared.
function sort(nums) {
function minIndex(left, right) {
const condition1 = right === nums.length;
const condition2 = !condition1 && nums[right] < nums[left>;
console.log(JSON.stringify({
condition: condition1 ? 1 : condition2 ? 2 : 3,
left: left,
right: right,
expression: condition1 ?
'DONE' : `${nums[right]} < ${nums[left]} = ${condition2}`
}))
if (condition1) { // 5a. condition
return left; // 6a. return?
} else if (condition2) { // 5b. condition
return minIndex(right, right + 1); // 6b. recursion, go back to 5a
} else { // 5c. condition
return minIndex(left, right + 1); // 6c. recursion, go back to 5a
}
}
for (let i = 0; i < nums.length; i++) { // 3. start loop
console.log(`LOOP: ${i + 1}/${nums.length}`);
let selected = minIndex(i, i + 1); // 4. find
if (i !== selected) { // 7. conditional
let tmp = nums[i]; // 8. begin swap
nums[i] = nums[selected]; // 9. swap
nums[selected] = tmp; // 10. complete swap, go back to 3
}
}
}
let nums = [10, 3, 5, 2, 4]; // 1. assignment
sort(nums); // 2. call function
console.log(nums); // 11. print sorted
.as-console-wrapper { top: 0; max-height: 100% !important; }