Beefy Boxes and Bandwidth Generously Provided by pair Networks RobOMonk
go ahead... be a heretic
 
PerlMonks  

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.


Comment on Re: Modified Binary Search
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (14)
As of 2014-04-16 14:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (430 votes), past polls