【发布时间】:2014-03-08 09:48:39
【问题描述】:
给定这里的算法,看看我在“X”的场景,会发生以下情况:
场景: i -> "X", "X" > "P"
1. swap("X", "Z"), gt--; // the value at i is now "Z", which is still > "P"
2. swap("Z", "Y"), gt--; // the value at i is now "Y", which is still > "P"
3. swap("Y", "C"), gt--; // Now we finally get a value at i "C" which is < "P"
// Now we can swap values at i and lt, and increrement them
4. swap("P", "C"), i++, lt++;
为什么我们不直接递减 gt 直到 gt 指向的值
因此,如果我们针对上述场景这样做,我们会这样做:
1. gt--
2. gt--
3. swap("X", "C"), gt--;
// Now we can swap values at i and lt, and increrement them
4. swap("P", "C"), i++, lt++;
算法是否需要这种过度交换?它会以某种方式提高性能吗? 如果它确实提高了性能,如何?
如果不影响性能,请给出适当的解释或证明,说明为什么它不会影响性能。
另外,我提到的第二种方法会以任何方式影响性能吗?请解释原因。
附:上面使用的“影响性能”是指提高/降低性能。
【问题讨论】:
标签: algorithm sorting quicksort