about summary refs log tree commit diff
path: root/src/sort/insertion.zig
diff options
context:
space:
mode:
authoriurii plugatarov <[email protected]>2024-07-28 21:07:00 +0200
committeriurii plugatarov <[email protected]>2024-07-28 21:07:00 +0200
commita679ae0a00adc299ab89efb69fad44ebab777d35 (patch)
tree243d4ce9ea0effe6fcf89e61cee80b10b562925d /src/sort/insertion.zig
downloaddsazitty-a679ae0a00adc299ab89efb69fad44ebab777d35.tar.gz
init
Diffstat (limited to 'src/sort/insertion.zig')
-rw-r--r--src/sort/insertion.zig19
1 files changed, 19 insertions, 0 deletions
diff --git a/src/sort/insertion.zig b/src/sort/insertion.zig
new file mode 100644
index 0000000..4aee57a
--- /dev/null
+++ b/src/sort/insertion.zig
@@ -0,0 +1,19 @@
+const std = @import("std");
+const mem = std.mem;
+const testing = std.testing;
+
+pub fn sort(comptime T: type, arr: []T) void {
+    for (1..arr.len) |i| {
+        var j = i;
+        while (j > 0 and arr[j - 1] > arr[j]) : (j -= 1) {
+            mem.swap(T, &arr[j - 1], &arr[j]);
+        }
+    }
+}
+
+test "insertion sort test" {
+    var arr = [_]i64{ 20, 3, 5, 1, 30, 4, 2 };
+    sort(i64, &arr);
+    const expected = [_]i64{ 1, 2, 3, 4, 5, 20, 30 };
+    try testing.expectEqualSlices(i64, &expected, &arr);
+}