Understanding Selection Sort Algorithm in JavaScript

--

source

Welcome to post # 3 of the series dedicated to exploring Algorithms with JavaScript.

What is Selection Sort?

Selection sort

The selection sorting algorithm divides the input list into two parts: a sorted sublist of items which is built up from left to right and a sublist of the remaining unsorted items. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest element in the unsorted sublist, swapping it with the leftmost unsorted element and moving the sublist boundaries one element to the right.

The time efficiency of selection sort is quadratic, so there are a number of sorting techniques which have better time complexity than selection sort.

One thing which distinguishes selection sort from other sorting algorithms is that it makes the minimum possible number of swaps, n − 1 in the worst case.

Implementation

Code

We have 3 functions:

swap - just changes the places of elements.

findMinValueIndex — finds minimum value in array and returns its index.

sort - is our main function which iterates through array finding the minimum element index from unsorted array and if minValueIndex is different then our current index, they are swapped.

--

--