Would the code below be the appropriate of implementing selection sort in Javascript?
let array = [24,27,43,11,32,7];
let temp;
for(i = 0; i<array.length; i++){
for(j =0; j<array.length; j++){
if(array[i] < array[j]){
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
console.log(array);
No.
With selection sort, you build up the sorted segment on the left side of the array in pieces by swapping the lowest value from the unsorted section with the next unsorted index. For an array of length N, there should be only N swaps - your approach is swapping many more times because it's not breaking to the next i after a swap. You also aren't identifying the lowest value in the unsorted section.
In the nested loop (over j), you should
i, not at 0 (because the portion of the array from 0 to i should already be sorted)j to the end of the array - this could be done with Math.min followed by indexOf, or by saving a variable of the lowest value found so far as well as its index, or with many other waysi index, then break so as to go onto the next iteration of iThat said - if this is anything other than an algorithm exercise, I'd highly recommend using the built-in Array.prototype.sort method for sorting an array; it's more concise, makes more sense at a glance, and is far faster.