I'm trying to implement selection sort with javascript, but it seems that either i'm missing something or doing something absolutely wrong.
as you may understand from a first look, sortArray() seems to return arr with only one value 5 while it should return an array with as such [5,5,5,5,5,5].
worth mentioning is that when I comment line smallest_index = find_smallest(nums)
I get the supposed input; [5,5,5,5,5,5].
let nums = [2, 1, 3, 4, 5, 6];
function sortArray(nums) {
let arr = new Array();
let smallest_index;
for (i = 0; i < nums.length; i++) {
smallest_index = find_smallest(nums);
arr.push("5");
}
return arr;
}
function find_smallest(arr) {
let smallest = arr[0];
let smallest_index = 0;
for (i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
console.log("this");
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
console.log(sortArray(nums));
any help or thoughts as to what i may be not be realizing or doing ?
ia local variable in each function.find_smallest()is updating the variableithat's used insortArray(), so the loop ends after the first iteration.for (let i = 0; i < nums.length; i++)letexists for a reason :)