Skip to main content

๐ŸŽฏ Selection Sort

This page provides introduction to Selection Sort.

Overviewโ€‹

Selection Sort is a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted part of the array and swapping it with the first element of the unsorted part. It continuously shrinks the unsorted portion of the array until the entire array is sorted.

Let's sort array below, with selection sort:

[64,25,12,22,11][64, 25, 12, 22, 11]

Step 1โ€‹

Find minimum element in whole unsorted array.

selection-sort-1.svg

Swap it with the first index of the unsorted array.

selection-sort-2.svg

Step 2โ€‹

Find minimum element in unsorted array.

selection-sort-3.svg

Swap it with the first index of the unsorted array.

selection-sort-4.svg

Step 3โ€‹

Find minimum element in unsorted array.

selection-sort-5.svg

Swap it with the first index of the unsorted array.

selection-sort-6.svg

Step 4โ€‹

Find minimum element in unsorted array.

selection-sort-7.svg

Swap it with the first index of the unsorted array.

selection-sort-8.svg
public void selectionSort(int[] arr) {
for(int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for(int j = i + 1; j < arr.length; j++) {
if(arr[minIndex] > arr[j]) {
minIndex = j
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}

Complexityโ€‹

Let's say there are N\text{N} elements in an array.

Time Complexityโ€‹

We are selecting minimum element from unsorted array which takes O(N)\text{O}(\text{N}) for each first index of the unsorted array, so total time complexity will be:

O(N2)\text{O}(\text{N}^2)

Space Complexityโ€‹

Algorithm uses constant space.

O(1)\text{O}(1)