Skip to content
DSA in JavaScript
Searching & Sorting

Selection Sort

Algorithm · Starter

Level: StarterSort First

Watch it run

5
2
8
1
9
3

Step 1 of 25

Selection sort: find the smallest value in the unsorted part and put it at the front.

Complexity

NameBestAverageWorstMemoryStableComments
Selection sortn2n2n21No

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

Code

SelectionSort.js
import Sort from '../Sort';

export default class SelectionSort extends Sort {
  sort(originalArray) {
    // Clone original array to prevent its modification.
    const array = [...originalArray];

    for (let i = 0; i < array.length - 1; i += 1) {
      let minIndex = i;

      // Call visiting callback.
      this.callbacks.visitingCallback(array[i]);

      // Find minimum element in the rest of array.
      for (let j = i + 1; j < array.length; j += 1) {
        // Call visiting callback.
        this.callbacks.visitingCallback(array[j]);

        if (this.comparator.lessThan(array[j], array[minIndex])) {
          minIndex = j;
        }
      }

      // If new minimum element has been found then swap it with current i-th element.
      if (minIndex !== i) {
        [array[i], array[minIndex]] = [array[minIndex], array[i]];
      }
    }

    return array;
  }
}

References

Wikipedia

Practice

Spotted a mistake or something unclear? Report it on GitHub.

On this page