about summary refs log tree commit diff
path: root/src/sort
diff options
context:
space:
mode:
Diffstat (limited to 'src/sort')
-rw-r--r--src/sort/bubble.zig20
-rw-r--r--src/sort/insertion.zig19
-rw-r--r--src/sort/selection.zig22
3 files changed, 61 insertions, 0 deletions
diff --git a/src/sort/bubble.zig b/src/sort/bubble.zig
new file mode 100644
index 0000000..5d868a2
--- /dev/null
+++ b/src/sort/bubble.zig
@@ -0,0 +1,20 @@
+const std = @import("std");
+const mem = std.mem;
+const testing = std.testing;
+
+pub fn sort(comptime T: type, arr: []T) void {
+    for (0..arr.len - 1) |i| {
+        for (i + 1..arr.len) |j| {
+            if (arr[i] > arr[j]) {
+                mem.swap(T, &arr[i], &arr[j]);
+            }
+        }
+    }
+}
+
+test "bubble_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.expectEqual(expected, arr);
+}
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);
+}
diff --git a/src/sort/selection.zig b/src/sort/selection.zig
new file mode 100644
index 0000000..0629680
--- /dev/null
+++ b/src/sort/selection.zig
@@ -0,0 +1,22 @@
+const std = @import("std");
+const mem = std.mem;
+const testing = std.testing;
+
+pub fn sort(comptime T: type, arr: []T) void {
+    for (0..arr.len - 1) |i| {
+        var min = i;
+        for (i + 1..arr.len) |j| {
+            if (arr[min] > arr[j]) {
+                min = j;
+            }
+        }
+        mem.swap(T, &arr[i], &arr[min]);
+    }
+}
+
+test "selection 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.expectEqual(expected, arr);
+}