JavaScript Selection Sort<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog

# JavaScript Selection Sort

Posted on: June 28, 2017

The selection sort is a very primitive sort that has two loops. They are both imbricated which cause an asymptotic analysis of the upper bound to be `O(n^2)`. The selection sort loops a first time all elements except the last one of the array which allow to evaluate every data. The second loop, is there to find the smallest value after the first loop and swap any smallest value if one found.

The idea is : find the smallest one, put it at the beginning.

`1function swap(array, left, right) {2  var temp = array[left];3  array[left] = array[right];4  array[right] = temp;5}6function selectionSort(arrayToSort) {7  var length = arrayToSort.length;8  var minIndex = -1;9  for (var i = 0; i < length - 1; i++) {10    minIndex = i;11    for (var j = i + 1; j < length; j++) {12      if (arrayToSort[j] < arrayToSort[minIndex]) {13        minIndex = j;14      }15    }16    if (minIndex !== i) {17      swap(arrayToSort, minIndex, i);18    }19  }20}`