Skip to content

Big O Visualizer

Selection Sort

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.

Complexity

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

Algorithm

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.quadratic
4 timeComplexityAverage = Complexities.quadratic
5 timeComplexityWorst = Complexities.quadratic
6
7 execute(array: number[]): void {
8 const len = array.length
9 for (let i = 0; i < len; i++) {
10 this.incrementOpCounter()
11 let min = i
12 for (let j = i + 1; j < len; j++) {
13 this.incrementOpCounter()
14 if (array[min] > array[j]) {
15 min = j
16 }
17 }
18 if (min !== i) {
19 const tmp = array[i]
20 array[i] = array[min]
21 array[min] = tmp
22 }
23 }
24 }
25}