This commit is contained in:
parent
a76aad6c8b
commit
6d6f2a58f2
5 changed files with 44 additions and 4 deletions
6
.github/workflows/testing.yml
vendored
6
.github/workflows/testing.yml
vendored
|
@ -22,5 +22,7 @@ jobs:
|
|||
run: zig build
|
||||
|
||||
- name: Test project
|
||||
run: zig build test --summary all
|
||||
|
||||
run: |
|
||||
zig fmt --check .
|
||||
zig build
|
||||
zig build test --summary all
|
||||
|
|
|
@ -8,7 +8,7 @@ This repository contains implementations of various search and sort algorithms i
|
|||
|
||||
- [x] Binary Search
|
||||
- [x] Jump Search
|
||||
- [ ] Interpolation Search
|
||||
- [x] Interpolation Search
|
||||
- [ ] Exponential Search
|
||||
- [ ] Fibonacci Search
|
||||
- [ ] Depth First Search (DFS)
|
||||
|
|
|
@ -4,7 +4,9 @@ const testing = std.testing;
|
|||
test {
|
||||
_ = BinarySearch;
|
||||
_ = JumpSearch;
|
||||
_ = InterpolationSearch;
|
||||
}
|
||||
|
||||
pub const BinarySearch = @import("search/binary-search.zig");
|
||||
pub const JumpSearch = @import("search/jump-search.zig");
|
||||
pub const InterpolationSearch = @import("search/interpolation-search.zig");
|
||||
|
|
36
src/search/interpolation-search.zig
Normal file
36
src/search/interpolation-search.zig
Normal file
|
@ -0,0 +1,36 @@
|
|||
/// Interpolation search
|
||||
///
|
||||
/// time complexity:
|
||||
/// space complexity:
|
||||
const std = @import("std");
|
||||
const testing = std.testing;
|
||||
const utils = @import("search_utils.zig");
|
||||
const assertInteger = utils.assertInteger;
|
||||
|
||||
pub fn search(array: anytype, target: @typeInfo(@TypeOf(array)).Array.child) ?@TypeOf(array[0]) {
|
||||
assertInteger(@TypeOf(array));
|
||||
|
||||
var left: usize = 0;
|
||||
var right: usize = array.len - 1;
|
||||
|
||||
while (left < right) {
|
||||
const probe: usize = @intCast(@as(i64, @intCast(left)) + @divTrunc(@as(i64, @intCast(right - left)) * (target - array[left]), (array[right] - array[left])));
|
||||
|
||||
if (array[probe] == target) {
|
||||
return target;
|
||||
}
|
||||
if (array[probe] < target) {
|
||||
left = probe + 1;
|
||||
}
|
||||
if (array[probe] > target) {
|
||||
right = probe;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
test "test interpolation search" {
|
||||
const array = [_]i64{ 1, 2, 4, 8, 16, 32, 64 };
|
||||
try testing.expectEqual(null, search(array, 5));
|
||||
try testing.expectEqual(4, search(array, 4));
|
||||
}
|
|
@ -2,7 +2,7 @@ pub fn assertInteger(comptime T: type) void {
|
|||
switch (@typeInfo(T)) {
|
||||
.Array => |info| switch (@typeInfo(info.child)) {
|
||||
.ComptimeInt, .Int => return,
|
||||
else => @compileError("not implemented for " ++ @typeName(T)),
|
||||
else => @compileError("not implemented for " ++ @typeName(T) ++ ", expected integer"),
|
||||
},
|
||||
else => @compileError("expects an array instead of " ++ @typeName(T)),
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue