๐ฏ 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:
Step 1โ
Find minimum element in whole unsorted array.
Swap it with the first index of the unsorted array.
Step 2โ
Find minimum element in unsorted array.
Swap it with the first index of the unsorted array.
Step 3โ
Find minimum element in unsorted array.
Swap it with the first index of the unsorted array.
Step 4โ
Find minimum element in unsorted array.
Swap it with the first index of the unsorted array.
- Java
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 elements in an array.
Time Complexityโ
We are selecting minimum element from unsorted array which takes for each first index of the unsorted array, so total time complexity will be:
Space Complexityโ
Algorithm uses constant space.