RosettaCodeData/Task/Binary-search/D/binary-search.d

42 lines
1.2 KiB
D
Raw Permalink Normal View History

2014-01-17 05:32:22 +00:00
import std.stdio, std.array, std.range, std.traits;
2013-04-10 16:57:12 -07:00
2014-01-17 05:32:22 +00:00
/// Recursive.
2015-02-20 00:35:01 -05:00
bool binarySearch(R, T)(/*in*/ R data, in T x) pure nothrow @nogc
if (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) {
2013-04-10 16:57:12 -07:00
if (data.empty)
return false;
immutable i = data.length / 2;
immutable mid = data[i];
2014-01-17 05:32:22 +00:00
if (mid > x)
return data[0 .. i].binarySearch(x);
if (mid < x)
return data[i + 1 .. $].binarySearch(x);
2013-04-10 16:57:12 -07:00
return true;
}
2014-01-17 05:32:22 +00:00
/// Iterative.
2015-02-20 00:35:01 -05:00
bool binarySearchIt(R, T)(/*in*/ R data, in T x) pure nothrow @nogc
if (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) {
2013-04-10 16:57:12 -07:00
while (!data.empty) {
immutable i = data.length / 2;
immutable mid = data[i];
2014-01-17 05:32:22 +00:00
if (mid > x)
2013-04-10 16:57:12 -07:00
data = data[0 .. i];
2014-01-17 05:32:22 +00:00
else if (mid < x)
data = data[i + 1 .. $];
2013-04-10 16:57:12 -07:00
else
return true;
}
return false;
}
void main() {
2014-01-17 05:32:22 +00:00
/*const*/ auto items = [2, 4, 6, 8, 9].assumeSorted;
2015-02-20 00:35:01 -05:00
foreach (const x; [1, 8, 10, 9, 5, 2])
2014-01-17 05:32:22 +00:00
writefln("%2d %5s %5s %5s", x,
items.binarySearch(x),
items.binarySearchIt(x),
// Standard Binary Search:
!items.equalRange(x).empty);
2013-04-10 16:57:12 -07:00
}