This code is to implement selection sort in JavaScript. I tried with the array [3,2,1] but it return [1,1,1]; the array [4,5,1,2,7] return [1,1,1,2,7]. I don’t know where I went wrong. Please help!
function selectionSort(a) {
var temp;
for (let i = 0; i < a.length - 1; i++) {
cur = a[i];
for (let j = i + 1; j < a.length; j++) {
if (a[j] < cur) {
cur = a[j];
}
}
if (a[i] != cur) {
temp = cur;
cur = a[i];
a[i] = temp;
}
}
return a;
}
console.log(selectionSort([4,5,1,2,7]));
2
Answers
The issue in your selection sort implementation is that you’re not swapping the values correctly when you find a smaller element in the inner loop. To fix the issue, you need to swap the elements by storing the current minimum value in a temporary variable and then assigning it to the correct position in the array.
use sort function for sorting array
function selectionSort(array) { array.sort( function(a,b) { return a-b } ); return array; }