Sorting

Selection Sort

Size:15
Visualizer is loading, please wait...
Execution Narrative
Step 1 of 174Start
Line 1
Starting Selection Sort on array of 15 elements.
Comparisons0
Swaps0
Operations0

Overview & Concept

Selection Sort is an in-place comparison sort that divides the array into a sorted sublist at the front and an unsorted sublist at the rear. It repeatedly finds the minimum element from the unsorted sublist and swaps it with the first unsorted element.

How It Works

Partitioning: Array is divided into sorted left prefix and unsorted right suffix.

Minimum Scanning: Scans the entire unsorted region to find the index of the absolute minimum value.

Single Swap per Pass: Exactly one swap is performed per outer iteration.

Deterministic O(n²): Performs the exact same number of comparisons regardless of initial array ordering.

Step-by-Step Execution

1. Initialize Minimum IndexSet minIndex = i for current pass position i.
2. Scan Unsorted SubarrayFor j = i + 1 to n - 1, compare A[j] with A[minIndex] and update minIndex if smaller.
3. Swap with PrefixIf minIndex != i, swap A[i] with A[minIndex].
4. Advance PartitionIncrement i and repeat until the array is fully sorted.

Asymptotic Complexity Analysis

MetricBest CaseAverage CaseWorst CaseSpace Complexity
Complexity BoundO(n²)O(n²)O(n²)O(1)
ExplanationOptimal input arrangement minimizing operations.Expected time for uniformly distributed randomized inputs.Adversarial degenerate conditions requiring full traversal.Auxiliary memory allocated beyond original input size.

Pseudocode & Invariants

Algorithm Logic
procedure selectionSort(A):
  n = length(A)
  for i = 0 to n - 2:
    minIdx = i
    for j = i + 1 to n - 1:
      if A[j] < A[minIdx]: minIdx = j
    end for
    if minIdx != i: swap(A[i], A[minIdx])
    mark A[i] as sorted
  return A
Algorithmic Invariants
  • Prefix Sortedness: Elements A[0..i-1] are sorted and all smaller than every element in A[i..n-1].
Correctness Guarantee: Invariants hold true prior to loop entry, are preserved during every iteration, and guarantee correct post-condition upon termination.

Advantages & Disadvantages

Key Advantages

  • •Minimizes writes: performs at most O(n) memory swap operations (useful when writes are expensive, like flash memory).
  • •In-place sorting with O(1) auxiliary memory.

Trade-offs & Limitations

  • •Strictly O(n²) comparisons even when input is already sorted.
  • •Unstable in its standard implementation.

Real-World Applications

EEPROM / Flash Memory Sorting

Writing to flash wears out memory cells; Selection Sort minimizes total write cycles.

Decision Guide: When to Use

Ideal Scenarios

  • ✓When memory write operations are significantly more costly than memory read comparisons.

Consider Alternatives When

  • ✕When sorting large datasets or when stability is required.

Compare trade-offs and complexity across complementary tools in AlgoViz.