By Hemanta Sundaray on 2021-09-20
Like, Bubble Sort, Selection Sort is a sorting algorithm.
The steps of Selection Sort are as follows:
Once we’ve determined which index contains the lowest value, we swap its value with the value we began the pass-through with. This would be index 0 in the first pass-through, index 1 in the second pass-through, and so on. The diagram above illustrates making the swap of the first pass-through.
Each pass-through consists of Steps 1 and 2. We repeat the pass-throughs until we reach a pass-through that would start at the end of the array. By this point, the array will have been fully sorted.
Here is an implementation of selection sort in JavaScript:
function selectionsort(arr) {
for (let i = 0; i < arr.length; i++) {
let indexOfMin = i
for (j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[indexOfMin]) {
indexOfMin = j
}
}
if (indexOfMin !== i) {
let lesser = arr[indexOfMin]
arr[indexOfMin] = arr[i]
arr[i] = lesser
}
}
return arr
}
console.log(selectionsort([6, 0, 25, -3, 4]))
// [ -3, 0, 4, 6, 25 ]