Implement Selection Sort in JavaScript

Michael Mitrakos
Published in
2 min readDec 24, 2022

--

Having worked across sites raking in over 50 billion website visits annually with Higglo Digital I write about tech topics and teach engineers to have solid foundations that will help them get ahead in their career. I also build awesome products for digital nomads — check it out!

Selection sort is a simple sorting algorithm that works by iterating through an array and selecting the minimum element. It then swaps this element with the first element in the array and repeats the process for the remaining elements until the entire array is sorted.

In JavaScript, we can implement selection sort using a for loop and a nested for loop to iterate through the array and find the minimum element. Here is an example of selection sort in JavaScript:

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

let arr = [5, 2, 1, 4, 3];
console.log(selectionSort(arr)); // [1, 2, 3, 4, 5]

In the above example, we have an array of integers that we want to sort in ascending order. The selectionSort function takes the array as an argument and uses a for loop to iterate through the array. For each iteration, it sets the minimum element to the current index and then uses a nested for loop to find the minimum element in the remaining portion of the array. If it finds a smaller element, it updates the minimum element to that index.

Finally, if the minimum element is not at the current index, it swaps the current element with the minimum element using a temporary variable. This process is repeated until the entire array is sorted.

Time Complexity

Selection sort has a time complexity of O(n²), making it less efficient than other sorting algorithms such as merge sort or quick sort. However, it is a simple algorithm to understand and implement, making it a good choice for software interviews or educational purposes.

I founded Higglo Digital and we can help your business crush the web game with an award-winning website and cutting-edge digital strategy. If you want to see a beautifully designed website, check us out.

I also created Wanderlust Extension to discover the most beautiful places across the world with highly curated content. Check it out!

--

--