Javascript Algorithms — Selection Sort

Kyle Jensen
Javascript Algorithms
2 min readFeb 19, 2018

--

The next algorithm we’ll discuss in this series is selection sort. Selection sort is a very simple, comparison algorithm that runs in O(n²) time. This algorithm is very simple and easy to implement, however it is also very inefficient (though not more so than bubble sort!).

The idea behind selection sort is that you loop through the input array linearly, selecting the first smallest element, and then swap it to the first position. Then you loop through the array again using a linear scan and get the second smallest element, swap it to the second position, and so on and so forth until your array is completely sorted. Easy right? Let’s look at the code:

let selectionSort = (arr) => {
let len = arr.length;
for (let i = 0; i < len; i++) {
let min = i;
for (let j = i + 1; j < len; j++) {
if (arr[min] > arr[j]) {
min = j;
}
}
if (min !== i) {
let tmp = arr[i];
arr[i] = arr[min];
arr[min] = tmp;
}
}
return arr;
}

The code itself is just as easy to read as the concept of selection sort is to explain. A personal preference of mine is to ensure that the value of “min” isn’t equal to “i” in order to avoid an unnecessary swap of the same item with itself (because what’s the point?).

That’s all for the selection sort, thanks for reading!

--

--

Kyle Jensen
Javascript Algorithms

Founder/CEO of Zealist (check us out!) & Polarity Labs. Twitter @_kylejensen