user13964720
user13964720

Reputation:

Don't understand how this code execution flows

I'm a beginner, I started learning JavaScript two weeks ago. Can anyone can show me what the execution steps are for the code below?

function sort(nums) {
  function minIndex(left, right) {
    if (right === nums.length) {
      return left;
    } else if (nums[right] < nums[left]) {
      return minIndex(right, right + 1);
    } else {
      return minIndex(left, right + 1);
    }
  }

  for (let i = 0; i < nums.length; i++) {
    let selected = minIndex(i, i + 1);
    if (i !== selected) {
      let tmp = nums[i];
      nums[i] = nums[selected];
      nums[selected] = tmp;
    }
  }
}

let nums = [10, 3, 5, 2, 4];
sort(nums);
console.log(nums);

Upvotes: 0

Views: 57

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48610

Each step is labeled 1-11.

Pay attention to the loops and recursive calls inside the code. I suggest you read about recursion for a better understanding, before diving into this code.

Edit: I added logging for each time the minIndex function is called, to show the current indices and what values are 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, goto 5a
    } else {                               // 5c. condition
      return minIndex(left, right + 1);    // 6c. recursion, goto 5a
    }
  }

  for (let i = 0; i < nums.length; i++) {  // 3. begin 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. finish swap, goto 3
    }
  }
}

let nums = [10, 3, 5, 2, 4];               // 1. assignment
sort(nums);                                // 2. function call
console.log(nums);                         // 11. print sorted
.as-console-wrapper { top: 0; max-height: 100% !important; }

Upvotes: 0

Related Questions