Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: Modified Binary Search

by sfink (Deacon)
on Jan 13, 2010 at 22:21 UTC ( #817292=note: print w/replies, xml ) Need Help??

in reply to Modified Binary Search

Sure, you could write two custom binary searches. The first would search out the boundary between $beg and anything smaller than it, rather than just looking for $beg. It's a slight modification to standard binary search. I'm pretty sure I've written it before. And it's no harder to get right than standard binary search -- as in, trivially easy in principle, but taking an embarrassingly long time in practice.

There's probably a clever way to do it purely by tweaking the comparison function passed to a binary search: when passed an index, treat it as referring to the border between the pair of adjacent elements. Only return zero (matching) if $array[$i] eq $probe && ($i == 0 || $array[$i-1] lt $probe).

Then you'd either do the same thing but for the other type of boundary for $end, or parameterize your code to do either one. (Once again, easy in theory, pain in the butt in practice.)

But... this only buys you something if you expect a *lot* of duplicates of $beg or $end. Is that the case? If not, just do your standard binary searches followed by linear scans to find the actual boundaries. Much, much easier to code up, and probably faster for most data sets.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://817292]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2022-08-18 01:22 GMT
Find Nodes?
    Voting Booth?

    No recent polls found