SimuVedaAlgorithms Lab Open in the lab

Sorting / Beginner

Selection Sort Visualizer

Find the smallest value in the unsorted part and swap it to the front. Repeat until nothing is left.

Start the Selection Sort simulation → Step forward and back, change the input, follow the code line by line in Java, Python, C++, C or JavaScript. Free, no sign-up.

Time and space complexity

Best timeO(n²)
Average timeO(n²)
Worst timeO(n²)
Extra spaceO(1)

Worked example, step by step

The same steps the simulator shows, on a small input.

  1. Selection sort on 5 values. [5, 1, 4, 2, 8]
  2. Start of pass 1: assume 5 at index 0 is the smallest.
  3. Is 1 smaller than the current minimum 5?
  4. Yes. The new minimum is 1.
  5. Is 4 smaller than the current minimum 1?
  6. Is 2 smaller than the current minimum 1?
  7. Is 8 smaller than the current minimum 1?
  8. Swap the minimum 1 into index 0. [1, 5, 4, 2, 8]
  9. Start of pass 2: assume 5 at index 1 is the smallest.
  10. Is 4 smaller than the current minimum 5?
  11. Yes. The new minimum is 4.
  12. Is 2 smaller than the current minimum 4?
  13. Yes. The new minimum is 2.
  14. Is 8 smaller than the current minimum 2?
  15. Swap the minimum 2 into index 1. [1, 2, 4, 5, 8]
  16. Start of pass 3: assume 4 at index 2 is the smallest.
  17. Is 5 smaller than the current minimum 4?
  18. Is 8 smaller than the current minimum 4?
  19. 4 is already the smallest. No swap needed.
  20. Start of pass 4: assume 5 at index 3 is the smallest.
  21. Is 8 smaller than the current minimum 5?
  22. 5 is already the smallest. No swap needed.
  23. Sorted. 10 comparisons and 2 swaps.

Try it with your own input →

Selection sort in Java, Python, C++, C and JavaScript

void selectionSort(int[] a) {
  for (int i = 0; i < a.length - 1; i++) {
    int min = i;
    for (int j = i + 1; j < a.length; j++) {
      if (a[j] < a[min]) {
        min = j;
      }
    }
    swap(a, i, min);
  }
}
def selection_sort(a):
    for i in range(len(a) - 1):
        min_i = i
        for j in range(i + 1, len(a)):
            if a[j] < a[min_i]:
                min_i = j
        a[i], a[min_i] = a[min_i], a[i]
void selectionSort(vector<int>& a) {
  int n = a.size();
  for (int i = 0; i < n - 1; i++) {
    int mn = i;
    for (int j = i + 1; j < n; j++) {
      if (a[j] < a[mn]) {
        mn = j;
      }
    }
    swap(a[i], a[mn]);
  }
}
void selectionSort(int a[], int n) {
  for (int i = 0; i < n - 1; i++) {
    int mn = i;
    for (int j = i + 1; j < n; j++) {
      if (a[j] < a[mn]) {
        mn = j;
      }
    }
    int t = a[i]; a[i] = a[mn]; a[mn] = t;
  }
}
function selectionSort(a) {
  for (let i = 0; i < a.length - 1; i++) {
    let min = i;
    for (let j = i + 1; j < a.length; j++) {
      if (a[j] < a[min]) {
        min = j;
      }
    }
    [a[i], a[min]] = [a[min], a[i]];
  }
}

In an interview

It makes at most n − 1 swaps, which matters when writing to memory is expensive. It is not stable.

More sorting