about summary refs log tree commit diff
path: root/src/sort/quick.zig
blob: 598331e5464c0aaaf968570dff27a6e05a26418f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const std = @import("std");
const testing = std.testing;
const mem = std.mem;

fn partition(comptime T: type, arr: []T, low: usize, high: usize) usize {
    const pivot = arr[high];
    var i: usize = low;

    for (low..high) |j| {
        if (arr[j] <= pivot) {
            mem.swap(T, &arr[i], &arr[j]);
            i += 1;
        }
    }
    mem.swap(T, &arr[i], &arr[high]);
    return i;
}

pub fn sort(comptime T: type, arr: []T, low: usize, high: usize) void {
    if (low < high) {
        const pivot_index = partition(T, arr, low, high);

        if (pivot_index > low) {
            sort(T, arr, low, pivot_index - 1);
        }
        sort(T, arr, pivot_index + 1, high);
    }
}

test "quick sort" {
    var arr = [_]i32{ 64, 34, 25, 12, 22, 11, 90 };
    sort(i32, &arr, 0, arr.len - 1);
    const expected = [_]i32{ 11, 12, 22, 25, 34, 64, 90 };
    try testing.expectEqualSlices(i32, &expected, &arr);
}