What is Selection Sort Algorithm?

Article By Digamber Rawat Published on
Selection sort algorithm begins with comparing the first two elements of an array and swapping when there is a need. If the selection sort is to be done in ascending order, then we have to check if the first element is higher than the second element then swapping is required.

This element is further checked with each of the other element, and the position is decided. However, if the first element is not more significant then swapping does not take place between the first and second elements.

DigitalOcean Affiliate

If the number of elements that are to be sorted is N in that case, the process of selection sort needs to be repeated n-1 times. The comparison usually starts in the second step, from the second element. This is because, after the initial step, the number which is required is sorted into the first position.

This means that the smallest number is usually sorted into the first position in case of ascending order, and the most significant number is sorted into the second position in case of descending order.

Similarly, the comparison starts with the third element in the third step, and this is how the process goes on.

Solving Selection Sort Algorithm in JavaScript

Selection sort algorithm is not that difficult and is easy to use. However, the other kinds of algorithm deals with sorting are some way or the other better than this. One of the biggest disadvantage of selection sort is that a large number of elements should not be sorted using this.

function selectionSort(array) {
for (var i = 0; i < array.length; i++) {
let min = i;
for (var j = i + 1; j < array.length; j++) {
if (array[min] > array[j]) {
min = j;
}
}
if (i !== min) {
[array[ i ],array[min]]= [array[min],array[ i ]];
}
}
return array
}
selectionSort([ 8, 4, 6, 1 ])
// Result: [1, 4, 6, 8]

Note: even though this is a program in JavaScript, the algorithm foe selection sort can also be very much similar to other languages in programming as well.

Selection Sort Time complexity

Best Average Worst
O(n^2) O(n^2) O(n^2)

In order to understand time and space complexity of Selection sort algorithm, Check out this awesome Big O cheat sheet.

Digamber Rawat
Digamber Rawat

I am a software engineer from India, love to learn and write about latest web and mobile technologies like: MongoDB, Angular 2+, Firebase, Express JS, Python, Node JS, JavaScript, RxJS etc.