Understanding Selection Sort Algorithm (in JavaScript!)

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).

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).

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.

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

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⚡️🎧🌙

--

--

MHA grad & Software Engineer | Rails | React | JavaScript | CSS | HTML

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tish Faroul

MHA grad & Software Engineer | Rails | React | JavaScript | CSS | HTML