ā¬ļøš Selection Sort
Back HomeSelection sort is a simple comparison-based sorting algorithm. It works by repeatedly finding the minimum element from the unsorted portion of the array and moving it to the end of the sorted portion. Each pass selects the next smallest element and places it in its final position until the whole array is sorted.
Java Implementation (well-commented)
// SelectionSort.java
// Simple implementation of selection sort in Java with comments.
public class SelectionSort {
// Sorts the input array in ascending order.
public static void selectionSort(int[] arr) {
int n = arr.length;
// Move the boundary of the unsorted subarray
// i is the index where the next minimum will be placed.
for (int i = 0; i < n - 1; i++) {
// Assume the element at i is the minimum.
int minIndex = i;
// Find the true minimum element in the unsorted portion (i+1 ... n-1).
for (int j = i + 1; j < n; j++) {
// If arr[j] is smaller than current min, update minIndex.
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// If we found a new minimum, swap it with the element at i.
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
// After this iteration, element at index i is in its final sorted position.
}
}
// Helper to print arrays (for demonstration)
public static void printArray(int[] arr) {
for (int x : arr) {
System.out.print(x + " ");
}
System.out.println();
}
// Example usage
public static void main(String[] args) {
int[] data = {64, 25, 12, 22, 11};
System.out.println("Before sort:");
printArray(data);
selectionSort(data);
System.out.println("After sort:");
printArray(data);
}
}
Interactive Visualization
Click any bar to edit its value (1ā10). Press Enter or click outside to confirm.
Pros & Cons
Pros: Selection sort is easy to understand and implement. It performs a small number of swaps ā at most nā1 swaps ā which can be helpful when write operations are expensive.
Cons: It has O(n²) time complexity for all cases (best, average, worst), making it inefficient for large arrays when compared to faster algorithms like quicksort or mergesort.
Best suited for
Selection sort is useful for small arrays, arrays where memory writes are costly, or educational purposes to demonstrate basic sorting mechanics.
Quick summary
Selection sort repeatedly finds the minimum element from the unsorted part and puts it at the beginning. It's simple and stable in terms of concept (not stable as an algorithm by default), but not efficient for large datasets.