计算数组中间索引的差异?

时间:2018-03-21 23:00:21

标签: java algorithm sorting average quicksort

我一直在尝试解决QuickSort,我通过一个场景来选择枢轴元素作为中间元素。

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];

我记得我之前也见过很多次。而且我确信我错过了一个场景,当我们得到奇数或其他东西时这会很有用。

我尝试了几个示例值,但我对这两种方式都得到了相同的响应。 我错过了什么?

感谢您的回复。

1 个答案:

答案 0 :(得分:1)

更有可能

  

(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)