Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast average without division

I have a binary search loop which gets hit many times in the execution path.

A profiler shows that the division part of the search (finding the middle index given the high and low indices of the search range) is actually the most costly part of the search, by a factor of about 4.

(I think) it is not critical for efficient binary search to find the exact middle value, just a value near the middle which does not have bias in either direction.

Is there a bit-twiddling algorithm to replace mid = (low + high) / 2 with something much faster?

Edit: Language is C#, but the equivalent bit-operation is valid in any language (although it may be of no performance benefit), which is why I left the C# tag off.

like image 462
Nick Avatar asked Jun 19 '09 21:06

Nick


People also ask

How do you find average without total?

new average = ((old count * old data) + next data) / next count. new average = old average + (next data - old average) / next count.

How do you divide without dividing?

Approach #1: Division using Repeated Subtraction We know that divisions can be solved by repeatedly subtracting the divisor from the dividend until it becomes less than the divisor. The total number of times the repeated subtraction is carried out is equal to the quotient.

How do I find the average number of something?

Average This is the arithmetic mean, and is calculated by adding a group of numbers and then dividing by the count of those numbers. For example, the average of 2, 3, 3, 5, 7, and 10 is 30 divided by 6, which is 5. Median The middle number of a group of numbers.


1 Answers

Here is a bit-hack version of the average that does not suffer from the overflow problem:

unsigned int average (unsigned int x, unsigned int y)
{
  return (x&y)+((x^y)>>1);
}
like image 157
Nils Pipenbrinck Avatar answered Sep 24 '22 11:09

Nils Pipenbrinck