about summary refs log tree commit diff
path: root/src/sort/selection.zig
blob: 0629680d4f10889a59dce2417fd701eaa3acfd86 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const std = @import("std");
const mem = std.mem;
const testing = std.testing;

pub fn sort(comptime T: type, arr: []T) void {
    for (0..arr.len - 1) |i| {
        var min = i;
        for (i + 1..arr.len) |j| {
            if (arr[min] > arr[j]) {
                min = j;
            }
        }
        mem.swap(T, &arr[i], &arr[min]);
    }
}

test "selection sort test" {
    var arr = [_]i64{ 20, 3, 5, 1, 30, 4, 2 };
    sort(i64, &arr);
    const expected = [_]i64{ 1, 2, 3, 4, 5, 20, 30 };
    try testing.expectEqual(expected, arr);
}