Skip to content

Instantly share code, notes, and snippets.

@50n1cd347h9
Last active October 24, 2024 19:48
Show Gist options
  • Save 50n1cd347h9/5fd8c653711245174b125c0c8ed8ba83 to your computer and use it in GitHub Desktop.
Save 50n1cd347h9/5fd8c653711245174b125c0c8ed8ba83 to your computer and use it in GitHub Desktop.
const std = @import("std");
const io = std.io;
const stdout = io.getStdOut().writer();

const N = 10;

pub fn main() !void {
    var a = [_]i32{ 41, 24, 76, 11, 45, 64, 21, 69, 19, 36 };

    quick(&a, 0, N - 1);

    for (0..N) |k| {
        try stdout.print("{d} ", .{a[k]});
    }
    try stdout.print("\n", .{});
}

fn quick(a: []i32, left: usize, right: usize) void {
    if (left < right) {
        const s = a[left];
        var i = left + 1;
        var j = right;

        while (true) {
            while (a[i] < s) : (i += 1) {}
            while (a[j] > s) : (j -= 1) {}

            if (i >= j) break;

            const tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }
        a[left] = a[j];
        a[j] = s;

        if (j > 0) quick(a, left, j - 1);
        quick(a, j + 1, right);
    }
}
zig run quick_sort.zig
11 19 21 24 36 41 45 64 69 76
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment