Selection Sort

Beginner Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

Selection Sort searches for the minimum in the unsorted area and swaps it to the next position. After i steps, the first i positions are finalized.

Always $\Theta(n^{2})$ comparisons, few swaps (at most n).

Diagram

Library sort for comparison: Sort an Array [1].

Where used

Only teaching and micro-cases. Demonstrates the selection idea; replace with library sorters in production.

Depth

Selection Sort divides the array into a sorted prefix and an unsorted remainder. In round i, the smallest element is searched in the remainder and placed at position i. After this, the prefix contains exactly the i plus one smallest values, counting duplicates.

The search for the minimum considers the remaining area regardless of how pre-sorted the input is. The number of actual swap operations, on the other hand, is bound to the number of rounds and can be omitted if the minimum is already in the front.

Difficulty levels

  1. Execute one round with minimum index and subsequent swap.
  2. Formulate the prefix invariant for correctness.
  3. Assess comparison and writing costs separately.

Pitfalls

The found value alone is not sufficient because its index is needed for the swap. In the case of multiple minima, the choice of occurrence also affects the relative order of identical keys.


Sources

University approvals: 0
Tasks
Question 1

How many swaps does Selection Sort make at most?

Question 2

What statement follows from the invariant after the completion of round i?

Question 3

Implement Selection Sort in ascending order and modify the array directly.

Hint

Array length and element access are called a.length and a[i]. For a swap, a local int variable is sufficient.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy