Searching string for character in binary search
Joel
joelcnz at gmail.com
Sun Feb 25 21:18:55 UTC 2018
The number tests work, but not the string one.
void main() {
assert([1,2,3,4,5,6,7,8,9,10,11].binarySearch(6));
assert(! [1,2,3,4,5,7,8,9,10,11].binarySearch(6));
assert("abcdefghijklmnopqrstuvwxyz".binarySearch('j')); // not
work
import std.stdio;
writeln("Assert tests passed!");
}
bool binarySearch(T)(T[] arr, T n) {
while(arr.length) {
auto i = arr.length/2;
if (arr[i] == n)
return true;
else
if (arr[i] > n)
arr = arr[i + 1 .. $];
else
arr = arr[0 .. i];
}
return false;
}
More information about the Digitalmars-d-learn
mailing list