Search code examples
javascriptalgorithmselection-sort

Why Does Using a Variable for the Index Work in This Selection Sort Algorithm in JavaScript?


I'm trying to understand why using a variable to assign the index works fine, instead of directly using the index itself in the following code snippet of the selection sort algorithm using JavaScript.

What I Tried:
I attempted to use the index of the minimum element directly (j):

let myArray = [7, 9, 4, 16, 2, 0, 4, -18];

function selectionSortAlgorithm(anArray) {
    for (let i = 0; i < anArray.length - 1; i++) {
        let min = anArray[i];

        for (let j = i + 1; j < anArray.length; j++) {
            if (min > anArray[j]) {
                min = anArray[j];
            }
        }
        let temp = anArray[i];
        anArray[i] = min;
        anArray[j] = temp;
    }
    return anArray;
}

console.log(selectionSortAlgorithm(myArray));

The Correct Code:
I found that using a new variable for the minimum element (minIndex) corrects the issue:

let myArray = [7, 9, 4, 16, 2, 0, 4, -18];

function selectionSortAlgorithm(anArray) {
    for (let i = 0; i < anArray.length - 1; i++) {
        let min = anArray[i];
        let minIndex = i;

        for (let j = i + 1; j < anArray.length; j++) {
            if (min > anArray[j]) {
                min = anArray[j];
                minIndex = j;
            }
        }
        let temp = anArray[i];
        anArray[i] = min;
        anArray[minIndex] = temp;
    }
    return anArray;
}

console.log(selectionSortAlgorithm(myArray));

Solution

  • The problem in your first code is that j is declared inside of for statement.

    for (let j = i + 1; j < anArray.length; j++) {
      if (min > anArray[j]) {
        min = anArray[j];
      }
    }
    

    So when you try to access it out of the statement, it isn't accessible

    ReferenceError: j is not define
    

    In the second example, you create let minIndex outside of the for statement. That's why you can access it.