Algorithm Action: Selection Sort

Nicholas Echevarria
2 min readDec 14, 2020
Photo by Jan Antonin Kolar on Unsplash

Algos, algos, algos: the cornerstone of a competent software engineer. This is why I’m compiling all my research and work on the topic in a series of articles titled Algorithm Action.

Today, we’re checking out a specific sorting pattern known as selection sort.

What is it?

Selection sort is similar to bubble sort, but instead of first placing large values into sorted position, it places small values into sorted position.

Interesting, but what’s the pseudocode like?

Let’s wrap our head around this one:

1. Store the first element as the smallest value you’ve seen so far in the given array. So if that’s 2, this variable will be equal to 2.
2. Compare this variable to the next element in the array until you find a smaller number.
3. If a smaller number is found, designate that smaller number to be the new minimum and continue until the end of the array.
4. If the minimum is not the value(index) you began with, swap the values.
5. Repeat this with the next element until the array is sorted.

Let’s code!

function selectionSort(arr) { 
for (var i = 0; i < arr.length; i++){
var min = i;
for (var j = i + 1; j < arr.length; j++){
if (arr[j] < arr[min]) {
min = j;
}
}
//swap the two elements
if (i !== min) {
var temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
return arr;
}

I truly hope this helps you!

--

--