Is it just me, or is there no binary search function in Phobos? I have a pre-sorted array that I want to search with my own comparator function, but I can't find anything in std.algorithms or std.containers.
Thanks!
Is it just me, or is there no binary search function in Phobos? I have a pre-sorted array that I want to search with my own comparator function, but I can't find anything in std.algorithms or std.containers.
Thanks!
Use SortedRange
from std.range
:
Cribbed from http://www.digitalmars.com/d/2.0/phobos/std_range.html#SortedRange:
auto a = [ 1, 2, 3, 42, 52, 64 ];
auto r = assumeSorted(a);
assert(r.canFind(3));
assert(!r.canFind(32));
find()
(and thus canFind()
) is actually pretty smart, using different algorithms based on what type input its given. In order for binary search to work, the data has to be sorted, so assumeSorted()
makes it so that it is, and then find()
and canFind()
are smart enough to know that binary search is the best search then, and that's what they do. –
Robey © 2022 - 2024 — McMap. All rights reserved.