Skip to content

Commit a4e95b1

Browse files
committed
insertion sort
1 parent d1c3c5f commit a4e95b1

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

zig/src/sorting.zig

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
const std = @import("std");
2+
const testing = std.testing;
3+
4+
pub fn insertion_sort(comptime T: type, array: []T) void {
5+
if (array.len == 0) {
6+
return;
7+
}
8+
9+
for (1..array.len) |i| {
10+
const current = array[i];
11+
12+
var j = i - 1;
13+
14+
while (j > 0 and array[j] > current) : (j -= 1) {
15+
array[j + 1] = array[j];
16+
}
17+
18+
array[j + 1] = current;
19+
}
20+
}
21+
22+
test {
23+
testing.refAllDecls(@This());
24+
}
25+
26+
test "insertion_sort" {
27+
var empty = [_]u32{};
28+
insertion_sort(u32, &empty);
29+
30+
var array = [_]u32{ 1, 5, 4, 2, 3 };
31+
32+
insertion_sort(u32, &array);
33+
34+
try testing.expectEqual(1, array[0]);
35+
try testing.expectEqual(2, array[1]);
36+
try testing.expectEqual(3, array[2]);
37+
try testing.expectEqual(4, array[3]);
38+
try testing.expectEqual(5, array[4]);
39+
}

0 commit comments

Comments
 (0)