Understanding Selection Sort Algorithm (in JavaScript!)

Tish Faroul
2 min readMay 22, 2022

--

Selection sort is not a very fast algorithm, but it is useful for searching through a list and sorting in a particular order (like smallest to largest values).

The algorithm compares the values in a list/array, in place.

We’ll begin by declaring our function and the return value (the sorted array).

function selectionSort(arr) {return arr;}

Next, we need to add the loop necessary to search through the length of the array.

We also need to declare a variable that will hold the index of our smallest value, assuming that the index is the smallest value (i).

function selectionSort(arr) {for (let i = 0; i < arr.length - 1; i++{  let smallest = i;
}
return arr}

We have the loop stop at one value less than the length of the array because in the next loop we will compare i with the next value, i+1

Now, we need to add a second loop that will compare the values in the array.

This loop will look for the smallest value, as previously declared by smallest.

function selectionSort(arr) {for (let i = 0; i < arr.length - 1; i++{  let smallest = i;for (let j = i + 1; j < arr.length; j++){}}return arr}

Now, we compare the values and swap them in the array.

If arr at j is smaller than the array at the smallest index, we’ll swap them to make the smallest index = j

function selectionSort(arr) {for (let i = 0; i < arr.length - 1; i++{let smallest = i;for (let j = i + 1; j < arr.length; j++){  if (arr[j] < arr[smallest]){
smallest = j;
}} [arr[i], arr[smallest]] = [arr[smallest], arr[i]];}return arr}

✨✨✨And that’s it!

Tish⚡️🎧🌙

--

--

Tish Faroul
Tish Faroul

No responses yet