Binary search: Difference between revisions

m
(→‎{{header|Zig}}: Add recursive example with slices)
 
(5 intermediate revisions by 3 users not shown)
Line 2,519:
{ p "Not found" }
{ p "Found at index: #{index}" }</syntaxhighlight>
 
=={{header|Bruijn}}==
<syntaxhighlight lang="bruijn">
:import std/Combinator .
:import std/Math .
:import std/List .
:import std/Option .
 
binary-search [y [[[[[2 <? 3 none go]]]]] (+0) --(∀0) 0]
go [compare-case eq lt gt (2 !! 0) 1] /²(3 + 2)
eq some 0
lt 5 4 --0 2 1
gt 5 ++0 3 2 1
 
# example using sorted list of x^3, x=[-50,50]
find [[map-or "not found" [0 : (1 !! 0)] (binary-search 0 1)] lst]
lst take (+100) ((\pow (+3)) <$> (iterate ++‣ (-50)))
 
:test (find (+100)) ("not found")
:test ((head (find (+125))) =? (+55)) ([[1]])
:test ((head (find (+117649))) =? (+99)) ([[1]])
</syntaxhighlight>
 
=={{header|C}}==
 
Line 2,868 ⟶ 2,891:
 
'''iterative''' -- almost a direct translation of the pseudocode
<syntaxhighlight lang="chapel">proc binsearch(A : [], value) {
{
var low = A.domain.dim(1).low;
var highlow = A.domain.dim(10).highlow;
whilevar (lowhigh <= highA.domain.dim(0) {.high;
while (low <= high)
{
var mid = (low + high) / 2;
 
Line 2,888 ⟶ 2,913:
{{out}}
4
 
=={{header|Clojure}}==
'''Recursive'''
Line 7,828 ⟶ 7,854:
]</syntaxhighlight>
=={{header|Wren}}==
<syntaxhighlight lang="ecmascriptwren">class BinarySearch {
static recursive(a, value, low, high) {
if (high < low) return -1
Line 7,889 ⟶ 7,915:
70 was not found in the array.
</pre>
 
=={{header|XPL0}}==
{{trans|C}}
Line 8,011 ⟶ 8,038:
====Recursive====
<syntaxhighlight lang="zig">pub fn binarySearch(comptime T: type, input: []const T, search_value: T) ?usize {
if (@sizeOf(T) == 0) return 0;
 
return binarySearchInner(T, input, search_value, @intFromPtr(input.ptr));
}
Line 8,018 ⟶ 8,043:
fn binarySearchInner(comptime T: type, input: []const T, search_value: T, start_address: usize) ?usize {
if (input.len == 0) return null;
if (@sizeOf(T) == 0) return 0;
 
const mid = (input.len - 1) / 2;
6

edits