in reply to Most Significant Set Bit
A binary search should be the 3rd alternative here. First alternative, if the problem space is only 64 bits, is a linear search through 64 bits. Second alternative should probably be a mathematical solution. And the third would be a binary search. It's really hard to make the complexity of a binary search beat the speed of a linear search for a small search set.
It's true that a binary search in a 64 bit unsigned integer range is going to take, at worst, 64 comparisons. And on average, a lot less than 64 comparisons, in a randomized data set of 64 bit numbers. This is O(log(n)). But a linear search through a 64-bit vector to find the most significant bit for an integer, is also O(log(n)); you have at most 64 comparisons with a binary search through 2**64 numbers, or you have at most 64 comparisons if you do a linear search through the bits of a number that fits within 64 bits. And a linear search will be very fast for such a small problem space.
But a mathematical solution to the problem is that the most significant bit of any unsigned integer will be found at index int(log2(n)). So if n is 1, int(log2(n)) is 0 (the zero-index bit; the right-most bit). The int(log2(32767)) is 15. You cannot represent 32767 in fewer than 16 bits. And the most significant bit will be the left-most bit, or the bit at index (offset) 15.
Therefore, a solution that requires NO iteration at all could be:
sub most_significant_ix { my $n = shift; return if $_[0] == 0; return int(log($_[0])/log(2)); }
Unfortunately the log function isn't inexpensive, so the linear search through 64 bits will probably still win, though on paper this solution is O(1), whereas the linear search through bits of an integer, and the binary search through the integer range, will both be O(log(n)) time complexity.
A linear search through the bits solution would look like this:
sub most_significant_ix { my $n = shift; return undef if $n == 0; my $bits = 64; while (--$bits >= 0) { return $bits if (2**$bits) & $n; } }
Dave
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Most Significant Set Bit
by hippo (Archbishop) on Mar 15, 2024 at 23:07 UTC | |
by Danny (Chaplain) on Mar 15, 2024 at 23:20 UTC | |
by ikegami (Patriarch) on Mar 18, 2024 at 15:05 UTC | |
Re^2: Most Significant Set Bit
by NERDVANA (Priest) on Mar 20, 2024 at 22:31 UTC | |
by davido (Cardinal) on Mar 22, 2024 at 19:42 UTC | |
by NERDVANA (Priest) on Mar 22, 2024 at 21:35 UTC | |
Re^2: Most Significant Set Bit
by Danny (Chaplain) on Mar 15, 2024 at 23:03 UTC |