What does `>> 1` mean?
I'm reading through the underscore.js code. I found this:
var mid = (low开发者_运维百科 + high) >> 1;
What does >> 1
do? Why is it useful?
It shifts the bits in the left side to the right by one bit. It is equivalent to dividing by 2.
In 'Ye olden times' this was faster than simply dividing, though I doubt it would make a whole lot of difference in underscore's case.
>>
is the sign propagating right shift operator. It shifts the bit pattern of (low + high)
right by 1
place and the leftmost bit is copied to the left place. It's effectively same as Math.floor((low + high) / 2)
.
I would be remiss if I didn't point out a subtle bug with using (low + high) >> 1
to compute the mid point of an array in binary search which can cause overflow. (low + high) >>> 1
where >>>
is zero filling right shift operator, is devoid of overflow bug.
That's a bitwise right shift. For integers, it is equivalent to dividing by two; for JavaScript numbers, it is roughly the same as Math.floor((low + high) / 2)
but avoids the floating point altogether.
It's probably there to keep the value an integer. Dividing by 2 here may convert the result to a floating point number in some cases, for example, if (low + high)
is odd.
The two operations are not exactly equivalent:
> (5+2)/2
3.5
> (5+2)>>1
3
For this particular use, though, there are better idioms for finding the midpoint of two numbers.
精彩评论