Median of 3 partitioning

纵然是瞬间 提交于 2019-12-01 20:50:11

The reason is that the algorithm does not only find the median, it also sorts the low, middle and high elements. After the three permutations you know that a[middle]<=a[high]. So you need only to partition the elements before high, because a[high] is greater or equal to pivot.

Let's look at an example: low=0, middle=4 and high=8. Your array is like this:

lowerOrEqualToPivot X X X pivot X X X greaterOrEqualToPivot

If you swap middle with high, you need to partition the 8 elements between brackets :

[ lowerOrEqualToPivot X X X greaterOrEqualToPivot X X X ] pivot

If you swap middle with high-1, you need to split only 7 elements:

[ lowerOrEqualToPivot X X X X X X ] pivot greaterOrEqualToPivot

By the way there is a bug in the first line:

int middle = ( low + high ) / 2; //Wrong
int middle = ( low + high ) >>> 1; //Correct

The reason is that if (low + high) is greater than Integer.MAX_VALUE you will have an overflow and middle will be a negative number. The second line will always give you a positive result.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!