Skip to content### Complexity

### Algorithm

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.

Selection Sort has a *quadratic* time complexity for all possible cases.

Below the implementation of Selection Sort as used on this page.

src/algorithms/selection-sort.ts

`1export default class SelectionSort extends Algorithm {2 name = "Selection Sort"3 timeComplexityBest = Complexities.quadratic4 timeComplexityAverage = Complexities.quadratic5 timeComplexityWorst = Complexities.quadratic67 execute(array: number[]): void {8 const len = array.length9 for (let i = 0; i < len; i++) {10 this.incrementOpCounter()11 let min = i12 for (let j = i + 1; j < len; j++) {13 this.incrementOpCounter()14 if (array[min] > array[j]) {15 min = j16 }17 }18 if (min !== i) {19 const tmp = array[i]20 array[i] = array[min]21 array[min] = tmp22 }23 }24 }25}`