Welcome to another entry in my Sorting Algorithms in JS series here on Dev! I've previously covered Insertion Sort in last week's post, so check that out if you're interested.

## Intro

In computer science, few tools are used quite as often as sorting algorithms. We rely on them every day as programmers and engineers to sift through data, and they're built into nearly every modern programming language in one way or another.

While using a language's built-in sorting functions may get the job done for most day-to-day work, it's important to understand what's going on under the hood, and what different sorting algorithms are actually doing and why they work the way they do. While it may not come up often, there's always the chance you may be asked to implement or explain a sorting algorithm in a technical interview setting, which is exactly what this post is here to prepare you for!

Today, we'll be looking at Selection Sort, another one of the fundamental sorting algorithms in Computer Science.

## What is Selection Sort?

The Wikipedia Page of Selection Sort describes the algorithm like so:

Selection sort is an in-place comparison sorting algorithm.

...

The algorithm divides the input list into two parts: a sorted sublist of items which is built up from left to right at the front (left) of the list and a sublist of the remaining unsorted items that occupy the rest of the list.Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.

This might be a bit confusing without a visualization, so here's an animation to help put it all into perspective (I recommend watching it a few times to get a grasp on what's happening):

As we traverse through the array in an initial loop, we push forward through the array with a second pointer in a nested loop at the same time, comparing each value to the starting value (beginning with our first loop's initial index.) If we find a lower value, we set *that* new value as our new lowest value to be compared against, and continue pushing.

By doing this, we ensure that each time we traverse through the array we will always find the *next lowest value*. When we reach the end of our second loop, we swap the lowest value with our very first initial index's value, and proceed to the next step.

This could also be done in reverse order, by searching for the largest values, if we were interested in sorting from highest to lowest. It's your choice!

## How efficient is it?

Selection Sort, while relatively simple to comprehend and implement, unfortunately lags behind other sorting algorithms like Quick Sort, Heap Sort, and Merge Sort for larger data sets.

However, since Selection Sort functions in-place and requires no auxiliary memory, it does have a space advantage over some other more complicated algorithms.

Generally speaking, Insertion Sort is likely to be a more performant alternative, although Selection Sort is still important to know and understand as a programmer and computer scientist.

Selection Sort has a *best case*, *worst case*, and *average case* runtime complexity of **O(n^2)**, meaning it will always be quadratic in nature.

## How do we implement it?

Here's where the fun starts!

Since we're implementing Insertion Sort in JavaScript, we'll be making use of modern ES6+ syntax to handle swapping elements in the array, which will help keep the number of lines of code that we need to write down.

Here's what the final algorithm will look like:

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

Let's break this down step by step.

First off, let's declare our function, its return value (the sorted array), and the initial loop in which we'll be doing all of our logic:

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

You might be wondering why we're telling our loop to stop at `array.length - 1`

rather than the normal `array.length`

. This is because in the next loop, we'll start by comparing `i`

against its neighbor `i + 1`

in the array. This means we'll need to stop our initial loop one index short of the full array length.

Next we'll declare the variable that will hold the *index* of our current *smallest element*, `minIndex`

, and the second loop that will do our comparison work:

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

As you can see, this loop starts at `i + 1`

, assigning that value to the pointer `j`

. The `minIndex`

variable is only set to `i`

as a temporary measure, since it will likely be changed within this loop. However, there is the chance that `i`

*will* in fact be the next smallest value in the unsorted section of the array and will simply stay where it is.

Last but not least, we'll add in the core comparison logic within our nested loop, as well as the ES6 swap that exchanges the two values once the loop completes:

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

As we went over back at the top of this tutorial, the core of Selection Sort is the idea of *selecting* the next lowest value and keeping track of it until we hit the end of the array, then swapping it with the right boundary of the sorted section of the array (our initial `i`

index.)

We do this here by evaluating if `array[j] < array[minIndex]`

. If it is, this means that `j`

should be swapped to the end of our sorted section (unless an even lower value is found.) We do this by setting `minIndex = j`

.

After this loop completes, we will have found the next lowest value in the unsorted section of the array, and will swap it into its proper place using ES6 `[a, b] = [b, a]`

syntax.

And that's it! We've successfully implemented a Selection Sort algorithm in JavaScript. Woohoo!

At this point it's worth revisiting the animation from earlier, that gives a visual representation of everything we just did in code:

If you've come this far, thanks so much for reading! I hope this was a helpful tutorial to anyone learning about sorting algorithms, JavaScript, or programming fundamentals in general.

I'll continue working through more sorting algorithms in future posts, so stay tuned!

## Top comments (1)

Really great article! Thank you for making.