Selection Sort Algorithm

A simple comparison-based sorting algorithm that selects the smallest element and places it in the sorted portion.

Understanding Selection Sort

Selection Sort is a simple comparison-based sorting algorithm that divides the input into a sorted and an unsorted region, and repeatedly selects the smallest (or largest) element from the unsorted region and moves it to the sorted region.

How it Works:

  1. Divide the List: The array is conceptually divided into two parts: the sorted portion at the left end and the unsorted portion at the right end (initially, the sorted portion is empty).
  2. Find the Minimum: Find the smallest element in the unsorted portion.
  3. Swap Elements: Swap the smallest element with the first element of the unsorted region.
  4. Expand the Sorted Region: The boundary between the regions moves one element to the right.
  5. Repeat: Continue this process until the entire array is sorted.

Complexity:

  • Time Complexity:
    • Best Case: O(n²)
    • Average Case: O(n²)
    • Worst Case: O(n²)
  • Space Complexity: O(1) - sorting is done in-place

Key Properties:

  • Not Stable: Selection sort doesn't preserve the relative order of equal elements
  • Not Adaptive: The time complexity remains O(n²) even if the array is partially sorted
  • In-place: Only requires a constant amount O(1) of additional memory space
  • Minimal Swaps: Makes only O(n) swaps, which can be advantageous when memory writes are expensive

When to Use Selection Sort:

  • When the array is small
  • When memory writes are significantly more expensive than reads
  • When auxiliary memory is limited
  • When simplicity of implementation is more important than efficiency

Advantages and Disadvantages:

Advantages:

  • Simple to implement and understand
  • Performs well on small arrays
  • Makes the minimum number of swaps (maximum of n-1 swaps)

Disadvantages:

  • Inefficient on large arrays with O(n²) time complexity
  • Not stable - relative ordering of equal elements may change
  • Not adaptive - performance doesn't improve for partially sorted arrays

Practical Applications:

Although selection sort is generally outperformed by more efficient algorithms like quicksort and mergesort for large datasets, it has some niche applications:

  • When memory writes (swaps) are expensive but comparisons are cheap
  • In embedded systems with limited memory
  • As a teaching tool to introduce sorting concepts
  • When a simple sorting implementation is needed for small datasets