我一直在试图解决QuickSort,并且通过一个场景,我们选择了pivot元素作为中间元素。
http://www.java2novice.com/java-sorting-algorithms/quick-sort/
// calculate pivot number, I am taking pivot as middle index number
int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];这与下面获得中间指数的方法有多大的区别?
int pivot = array[(lowerIndex+higherIndex)/2];我记得我以前也见过这么多次。我肯定我错过了这样一种情况,当我们得到一个奇数或什么的时候,这是有帮助的。
我尝试了几个示例值,但两种方法都得到了相同的响应。我遗漏了什么?
谢谢你的回答。
发布于 2018-03-21 23:06:34
更有可能
(lowerIndex+higherIndex)/2
溢流而非溢出
lowerIndex+(higherIndex-lowerIndex)/2.
例如,对于lowerIndex == higherIndex == Integer.MAX_VALUE / 2 + 1。
编辑:
表达式等价性的数学证明
l + (r - l)/2 (in java notation)
= l + round_towards_zero((r - l) / 2) (in math notation)
= round_towards_zero(l + (r - l) / 2) (since l is an integer)
= round_towards_zero((2 * l + r - l) / 2)
= round_towards_zero(r + l) / 2)
= (l + r) / 2 (in java notation)https://stackoverflow.com/questions/49417881
复制相似问题