Selection sort
Sort an integer array in ascending order using selection sort.
Course progress
Problem 21 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [9, 5, 1, 7, 3]
Expected output
1 3 5 7 9
What is happening?
Each pass selects the smallest value in the unsorted suffix and moves it to the next output position, yielding ascending order.
Solution strategy
Build the right mental model
For each position, find the smallest value in the remaining unsorted suffix and swap it into place.
Core concepts
sorting · nested loops
Complexity
Time O(n^2), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for selection-sort
using System;
class Program
{
static void SelectionSort(int[] numbers)
{
for (int start = 0; start < numbers.Length - 1; start++)
{
int smallest = start;
for (int i = start + 1; i < numbers.Length; i++)
if (numbers[i] < numbers[smallest]) smallest = i;
int temporary = numbers[start];
numbers[start] = numbers[smallest];
numbers[smallest] = temporary;
}
}
static void Main()
{
int[] values = { 9, 5, 1, 7, 3 };
SelectionSort(values);
Console.WriteLine(string.Join(" ", values));
}
}Knowledge check
Questions students often ask
What is the main idea behind selection sort?
For each position, find the smallest value in the remaining unsorted suffix and swap it into place.
What is the time and space complexity of this solution?
Time O(n^2), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.