Selection Sort

Ayumi Tanaka
Algorithm Novice
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]
  1. Declare minIndex is equal to i.
  2. If arr[j] is less than arr[minIndex], return minIndex is equal to j.
  3. Iterate 2. until j become to be equal to arr.length-1. (Which means it would be conditioned j < arr.length)
  4. arr[i] , arr[minIndex] will be arr[minIndex], arr[i].
  5. Iterate 1. - 4. until i become to be equal to arr.length-2. (Which means it would be conditioned i < arr.length-1)
1st loop (i)i = 0
minIndex = 0
1st loop (j)j = 0
arr[0] < arr[0] // ? 3 < 3 // False
2nd loop (j)j = 1
arr[1] < arr[0] // ? 2 < 3 // True
minIndex = 1
3rd 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]

--

--