Skip to content

Instantly share code, notes, and snippets.

@g-w1
Created August 31, 2024 21:44
Show Gist options
  • Select an option

  • Save g-w1/681f97e78b24db23b646dab292b94e9b to your computer and use it in GitHub Desktop.

Select an option

Save g-w1/681f97e78b24db23b646dab292b94e9b to your computer and use it in GitHub Desktop.
const std = @import("std");
const buffer_size = 100_000_000;
var m = std.mem.zeroes([buffer_size]u64);
var default_prng = std.Random.DefaultPrng.init(0x420);
pub fn main() void {
const a = &m;
var in: usize = 0;
while (in < buffer_size) : (in += 1) {
m[in] = default_prng.next();
}
quicksort(a);
assert_sorted(a);
}
fn assert_sorted(a: []u64) void {
var i: usize = 0;
while (i < a.len - 1) : (i += 1) {
if (a[i] > a[i + 1]) {
@panic("not sorted");
}
}
}
fn quicksort(a: []u64) void {
if (a.len > 1) {
const p = partition(a);
quicksort(a[0..p]);
quicksort(a[p..a.len]);
}
}
fn partition(a: []u64) usize {
const part_val = a[a.len - 1];
var i: usize = 0;
var j: usize = 0;
while (j < a.len) {
if (a[j] <= part_val) {
swap(a, i, j);
i += 1;
}
j += 1;
}
return i - 1; // the last elements are after the partition, so we want to keep them this way
}
fn swap(a: []u64, i: usize, j: usize) void {
if (i != j) {
const temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment