Last active
June 17, 2023 11:54
-
-
Save kassane/b4afca62636fe08b950691d190fce5ac to your computer and use it in GitHub Desktop.
Sleepsort algorithm on Zig language
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//! 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