Selection Sort
Published in
1 min readOct 1, 2020
Q. Write an algorithm that performs selection sort on a given array.
let nums = [3, 2, 1];const selectionSort = function (arr) { for (let i = 0; i < arr.length - 1; i++) { let minIndex = i; for (let j = i + 1; j < arr.length; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } [arr[i], arr[minIndex] = [arr[minIndex], arr[i]]; } return arr;}console.log(selectionSort(nums));// should be [ 1, 2, 3]
- Declare
minIndex
is equal toi
. - If
arr[j]
is less thanarr[minIndex]
, returnminIndex
is equal toj
. - Iterate 2. until
j
become to be equal toarr.length-1
. (Which means it would be conditionedj < arr.length
) arr[i]
,arr[minIndex]
will bearr[minIndex]
,arr[i]
.- Iterate 1. - 4. until
i
become to be equal toarr.length-2
. (Which means it would be conditionedi < arr.length-1
)
1st loop (i)i = 0
minIndex = 01st loop (j)j = 0
arr[0] < arr[0] // ? 3 < 3 // False2nd loop (j)j = 1
arr[1] < arr[0] // ? 2 < 3 // True
minIndex = 13rd loop (j)j = 2
arr[2] < arr[1] // ? 1 < 3 // True
minIndex = 2
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]][3, 2, 1] = [1, 2, 3]