Skip to content

Instantly share code, notes, and snippets.

@kassane
Last active June 17, 2023 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kassane/b4afca62636fe08b950691d190fce5ac to your computer and use it in GitHub Desktop.
Save kassane/b4afca62636fe08b950691d190fce5ac to your computer and use it in GitHub Desktop.
Sleepsort algorithm on Zig language
//! Zig version: 0.11.0 (std.Thread.Pool)
const std = @import("std");
pub fn main() !void {
std.debug.print("Sleep sorting\n", .{});
const values = [_]usize{ 9, 40, 10, 1, 6, 45, 23, 50 };
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = arena.allocator();
defer arena.deinit();
std.debug.print("Sort numbers\n", .{});
try sleepSort([values.len]usize, values, allocator);
std.debug.print("\n", .{});
}
fn sleepSort(comptime T: type, nums: T, alloc: std.mem.Allocator) !void {
var threadpool: std.Thread.Pool = undefined;
try threadpool.init(.{ .allocator = alloc });
defer threadpool.deinit();
for (nums) |num| {
try threadpool.spawn(sleep, .{num});
}
}
fn sleep(num: usize) void {
std.time.sleep(num * std.time.ns_per_ms);
std.debug.print("{} ", .{num});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment