http://www.perlmonks.org?node_id=817383

in reply to Re^3: Modified Binary Search

I don't believe it is possible to code a search over sorted data with duplicates that comes even close to be O(log N). Even in theory.
You're wrong. You can easily find the smallest index containing your target value by using a condition like:
```return \$i if \$A[\$i] == \$target && (\$i == 0 || \$A[\$i-1] < \$target);
```return \$i if \$A[\$i] == \$target;
And you find the highest index by using:
```return \$i if \$A[\$i] == \$target && (\$i == \$#A || \$A[\$i+1] > \$target);
It doesn't increase the run time complexity - the worst case of a binary search is when no match is found anyway.

Replies are listed 'Best First'.
Re^5: Modified Binary Search
by BrowserUk (Pope) on Jan 14, 2010 at 11:55 UTC
You can easily find the smallest index containing your target value

How about finding the smallest index that contains a value equal or greater than your target; or highest equal or less?

And how about you post a full sub save all of us trying to recreate your thought?

It doesn't increase the run time complexity

The proof is in the pudding!

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
How about finding the smallest index that contains a value equal or greater than your target
```sub binary_search {
my (\$str, \$a) = @_;
my \$l = 0;
my \$h = @\$a;
while (\$l < \$h) {
my \$p = int ((\$l + \$h) / 2);
if (\$a->[\$p] lt \$str) {
\$l = \$p + 1;
}
else {
\$h = \$p;
}
}
\$l
}

update: minor changes to the sub.

How about finding the smallest index that contains a value equal or greater than your target; or highest equal or less?
That doesn't change the complexity.
And how about you post a full sub save all of us trying to recreate your thought?
Too much work to type out all the details.
The proof is in the pudding!
Get any textbook about introductions to algorithms.
That doesn't change the complexity.

Rubbish!

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
Re^5: Modified Binary Search
by Anonymous Monk on Aug 11, 2011 at 15:30 UTC
superb....