Initial array
Selection Sort builds the sorted prefix from left to right.
C programming · Lesson
Observe the minimum candidate, comparisons, and the swap that fixes one position at a time.
On each pass Selection Sort finds the minimum in the unsorted region and moves it into the first free position of the sorted prefix.
choose i → find minimum from i+1 → swap with v[i] → sorted prefix grows
The flowchart keeps algorithm control visible; the Array Lab below makes cells, indices, comparisons, candidates and swaps visible.
Indices stay visible at all times. Sorting traces highlight comparisons, the current candidate, swaps and the region already sorted.
Selection Sort builds the sorted prefix from left to right.
For now assume the minimum is v[0] = 5.
2 is smaller: the new minimum index is 1.
The provisional minimum does not change.
1 is smaller: the new minimum index is 3.
The provisional minimum does not change.
Position 0 is now final: it contains 1.
For now assume the minimum is v[1] = 2.
The provisional minimum does not change.
The provisional minimum does not change.
The provisional minimum does not change.
Position 1 is now final: it contains 2.
For now assume the minimum is v[2] = 4.
The provisional minimum does not change.
3 is smaller: the new minimum index is 4.
Position 2 is now final: it contains 3.
For now assume the minimum is v[3] = 5.
4 is smaller: the new minimum index is 4.
Position 3 is now final: it contains 4.
All positions are in ascending order.
Run C executes only the example shown on the left, using stdin on the right. The coding challenge below has a separate editor and test button.
1#include <stdio.h>
2
3int main(void)
4{
5 int v[5] = {5, 2, 4, 1, 3};
6 for (int i = 0; i < 4; i = i + 1)
7 {
8 int minimo = i;
9 for (int j = i + 1; j < 5; j = j + 1)
10 {
11 if (v[j] < v[minimo])
12 minimo = j;
13 }
14 int temp = v[i];
15 v[i] = v[minimo];
16 v[minimo] = temp;
17 }
18
19 for (int i = 0; i < 5; i = i + 1)
20 printf("%d\n", v[i]);
21 return 0;
22}
Read five integers, swap the minimum into index zero, then print the array.
This is a different program from lab 1. Complete the starter code: Check all test cases compiles this editor and tests every input, including boundary cases.
After the first pass over {5, 2, 4, 1, 3}, which value ends up at position 0?
Challenge 1 / 5 · Understanding
Progress: 0 / 5 · correct: 0
ConceptStep separates what is required from what is recommended or useful as reinforcement. Only required prerequisites block your progress.
Relationships: solid line = required · dashed line = recommended · dotted line = reinforcement.