Tell us what’s happening:
I am not sure what’s wrong with this selection sort algorithm. I should be looping through each item in the array and swapping it with the minimum value between it and the end of the array.
This algorithm works when there are no duplicate values:
console.log(selectionSort([5, 3, 2, 1, 4])); // returns [1, 2, 3, 4, 5]
It does not work when duplicates are present:
console.log(selectionSort([5, 3, 2, 1, 3])); // returns [1, 2, 5, 3, 3]
What am I missing?
Your code so far
function selectionSort(array) {
// change code below this line
// Loop through the array
for (let i = 0; i < array.length; i++) {
// Save the current item
const currval = array[i];
// Find the minimum item from the current index to the end
const minval = Math.min(...array.slice(i));
// Save the index of the minval
const mindex = array.indexOf(minval);
// If the current value is greater than the minimum value
if (currval > minval) {
// Swap the two in place
array[i] = minval;
array[mindex] = currval;
}
}
// change code above this line
return array;
}
// test array:
// [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
Your browser information:
User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/algorithms/implement-selection-sort/