The >>
operator performs a bit shift.
The expression >> 1
is almost* the same as / 2
so the programmer was calculating the index colorList.Count / 2
which is** the median. To understand why this is the case you need to look at the binary representation of the numbers involved. For example if you have 25 elements in your list:
n : 0 0 0 1 1 0 0 1 = 25
n >> 1: 0 0 0 0 1 1 0 0 = 12
In general using a bitwise operator when really you want to perform a division is a bad practice. It is probably a premature optimization made because the programmer thought it would be faster to perform a bitwise operation instead of a division. It would be much clearer to write a division and I wouldn't be surprised if the performance of the two approaches is comparable.
*The expression x >> 1
gives the same result as x / 2
for all positive integers and all negative even integers. However it gives a different result for negative odd integers. For example -101 >> 1 == -51
whereas -101 / 2 == -50
.
**Actually the median is only defined this way if the list has an odd number of elements. For an even number of elements this method will strictly speaking not give the median.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…