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));
2
Answers
Credit to @AztecCodes
What makes you think that j would contain the index of the Min element? –
The index j in the inner loop of the first attempt is not the index of the minimum value. j is always anArray.length when that loop terminates. It finds the minimum value but forgets the index where it's found.
If you put console.log(j); in the first version and console.log(minIndex) in the second version, you'll see the difference.
The problem in your first code is that
j
is declared inside offor
statement.So when you try to access it out of the statement, it isn’t accessible
In the second example, you create
let minIndex
outside of thefor
statement. That’s why you can access it.