Selection sort
Find a smallest remaining item and exchange it with the first unsorted item. That position is now final.
Simple example
Select 1 for the first position and then 2 for the second. Print the sorted sequence.
Start3 1 2
Result1 2 3
const std = @import("std");
fn show(value: i64) !void {
var buffer: [64]u8 = undefined;
var writer = std.fs.File.stdout().writer(&buffer);
try writer.interface.print("{d}\n", .{value});
try writer.interface.flush();
}
pub fn main() !void {
var values = [_]i64{3, 1, 2};
var i: i64 = 0;
while (i < 2) {
var smallest: i64 = i;
var j: i64 = (i + 1);
while (j < 3) {
if (values[@intCast(j)] < values[@intCast(smallest)]) {
smallest = j;
}
j += 1;
}
const saved: i64 = values[@intCast(i)];
values[@intCast(i)] = values[@intCast(smallest)];
values[@intCast(smallest)] = saved;
i += 1;
}
i = 0;
while (i < 3) {
try show(values[@intCast(i)]);
i += 1;
}
}
1 2 3
Advertisements
Everyday examples
Load light parcels first
Parcels weigh 8, 3 and 5 kilograms. Which should occupy the first loading position?
Start8 3 5
Result3 8 5
Scan all three, then exchange 3 with the parcel at the front.
Choose the earliest date
Unsorted forms show days 9, 12 and 4. Which date goes in the first tray?
Start9 12 4
Result4
Reading the first two dates alone would miss day 4.
Finish a shelf in place
Books 1 and 2 are already fixed. Only books 5 and 3 remain. Which section needs scanning?
Start1 2 • 5 3
Result1 2 3 5
Leave the fixed prefix alone. Select 3 from the remaining pair and move it into place.
Cost and limits
Selection sort scans the remaining items even when they are in order. It uses O(n²) comparisons and at most n−1 swaps.