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));
The problem in your first code is that
jis declared inside offorstatement.So when you try to access it out of the statement, it isn't accessible
In the second example, you create
let minIndexoutside of theforstatement. That's why you can access it.