Binary search: Difference between revisions
Content added Content deleted
(Add Zig examples using slices or indexes, for now iterative only.) |
(→{{header|Zig}}: Add recursive example with indexes) |
||
Line 8,013: | Line 8,013: | ||
====Iterative==== |
====Iterative==== |
||
<syntaxhighlight lang="zig">const |
<syntaxhighlight lang="zig">const math = @import("std").math; |
||
fn binarySearch(comptime T: type, |
pub fn binarySearch(comptime T: type, input: []const T, search_value: T) ?usize { |
||
if (@sizeOf(T) == 0) { |
if (@sizeOf(T) == 0) { |
||
return if ( |
return if (input.len != 0) &input[0] else null; |
||
} |
} |
||
var low: usize = 0; |
var low: usize = 0; |
||
var high: usize = |
var high: usize = input.len - 1; |
||
return while (low <= high) { |
return while (low <= high) { |
||
const mid = ((high - low) / 2) + low; |
const mid = ((high - low) / 2) + low; |
||
const mid_elem: T = |
const mid_elem: T = input[mid]; |
||
if (mid_elem > search_value) |
if (mid_elem > search_value) |
||
high = |
high = math.sub(usize, mid, 1) catch break null |
||
else if (mid_elem < search_value) |
else if (mid_elem < search_value) |
||
low = mid + 1 |
low = mid + 1 |
||
Line 8,032: | Line 8,032: | ||
break mid; |
break mid; |
||
} else null; |
} else null; |
||
}</syntaxhighlight> |
|||
====Recursive==== |
|||
<syntaxhighlight lang="zig">const math = @import("std").math; |
|||
pub fn binarySearch(comptime T: type, input: []const T, search_value: T) ?usize { |
|||
return binarySearchInner(T, input, search_value, 0, input.len - 1); |
|||
} |
|||
fn binarySearchInner(comptime T: type, input: []const T, search_value: T, low: usize, high: usize) ?usize { |
|||
if (@sizeOf(T) == 0) { |
|||
return if (input.len != 0) &input[0] else null; |
|||
} |
|||
if (low > high) return null; |
|||
const mid = ((high - low) / 2) + low; |
|||
const mid_elem: T = input[mid]; |
|||
return if (mid_elem > search_value) |
|||
binarySearchInner(T, input, search_value, low, math.sub(usize, mid, 1) catch return null) |
|||
else if (mid_elem < search_value) |
|||
binarySearchInner(T, input, search_value, mid + 1, high) |
|||
else |
|||
mid; |
|||
}</syntaxhighlight> |
}</syntaxhighlight> |
||