Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Every project is managed by the `build.zig` file.
├── runall.sh
├── search
│ ├── binarySearchTree.zig
│ ├── linearSearch.zig
│ └── redBlackTrees.zig
├── sort
│ ├── bubbleSort.zig
Expand Down
7 changes: 7 additions & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ pub fn build(b: *std.Build) void {
.name = "redBlackTrees.zig",
.category = "search",
});
if (std.mem.eql(u8, op, "search/linearSearch"))
buildAlgorithm(b, .{
.optimize = optimize,
.target = target,
.name = "linearSearch.zig",
.category = "search",
});

// Data Structures algorithms
if (std.mem.eql(u8, op, "ds/trie"))
Expand Down
1 change: 1 addition & 0 deletions runall.zig
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ pub fn main() !void {
// Search
try runTest(allocator, "search/bSearchTree");
try runTest(allocator, "search/rb");
try runTest(allocator, "search/linearSearch");

// Threads
try runTest(allocator, "threads/threadpool");
Expand Down
56 changes: 56 additions & 0 deletions search/linearSearch.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const std = @import("std");
const expect = std.testing.expect;
const expectError = std.testing.expectError;

const searchErrors = error{KeyNotFound};

// returns the index of the first occurrence of key
fn search(arr: []i32, key: i32) !usize {
for (arr, 0..) |v, i| {
if (v == key) {
return i;
}
}
return searchErrors.KeyNotFound;
}

test "empty array" {
var A = [_]i32{};
try expectError(searchErrors.KeyNotFound, search(A[0..], 5));
}

test "single element array, key not in array" {
var A = [_]i32{2};
try expectError(searchErrors.KeyNotFound, search(A[0..], 5));
}

// to test off-by-one errors
test "2 element array" {
var A = [_]i32{ 2, 8 };
try expect(try search(A[0..], 8) == 1);
}

test "key at last" {
var A = [_]i32{ 2, 3, 6, 0, 1, 7, 8, 9 };
try expect(try search(A[0..], 9) == 7);
}

test "key not in array" {
var A = [_]i32{ 2, 3, 6, 0, 1, 7, 8, 9 };
try expectError(searchErrors.KeyNotFound, search(A[0..], 5));
}

test "duplicate elements in array" {
var A = [_]i32{ 2, 3, 6, 0, 1, 7, 8, 1, 9 };
try expect(try search(A[0..], 1) == 4);
}

test "negative numbers" {
var A = [_]i32{ 2, -3, 6, 0, 1, -7, 8, -1, 9 };
try expect(try search(A[0..], -1) == 7);
}

test "identical elements" {
var A = [_]i32{ 0, 0, 0, 0, 0, 0, 0, 0 };
try expect(try search(A[0..], 0) == 0);
}