Hello, I have a general question (unrelated to any particular challenge) in regard to loops and assigning containers for certain processes related to an algorithm. This is the big thing I’m still struggling with in regard to loops and probably JS in general. Below I have an example of my query. I’ll write the setup for the code and the code itself. I’ve put my queries within it. (The problem is from a book entitled “A Common Sense Guide to Data Structures and Algorithms”
Sort the array in order from least to greatest
var array =[4,2,7,1,3]
function selectionSort(array) {
for(var(i=0;i<array.length;i++){
var lowestNumberIndex = i;
//this is assigned to i, but why would I think that i would automatically point to the index with the lowest number? I iterates through all of them and every number would be less than the total length of the array, correct?
for(var j = i + 1;j < array.length; j++) {
if(array[j] < array[lowestNumberIndex]) {
lowestNumberIndex = j;
}
//One why does assigning i+1 to var j make a difference i determining the index of the lowest number? var i and var j are just variables iterating through an array of numbers. Each single number will be less than the length of the entire array of numbers, correct?
}
if(lowestNumberIndex !== i) {
var temp = array[i];
array[i] = array[lowestNumberIndex];
array[lowestNumberIndex] = temp;
}
//If the idea is to swap the lowest number for the number at the position the lowest number should be at, then I don't understand how switching the assignments does this.(1) and I don't understand how var i and var lowestNumberIndex have their particular valence in the function when they seem arbitrary parts of the loop (They aren't methods like .minMax or something like this that actually find the lowest element in an array.)
}
return array
}
I’m really looking for someone to explain to me how things are working when they seem to me to be arbitrary assignments.
Thank you for the patience of anyone willing to explain this to me.