我在看this简单实现QuickSort算法。
我遇到分区方法的问题。我重新命名变量以帮助我理解。我理解大部分方法,但有一个变量的目的我没有得到。这是store
变量。
这是我的这个方法的版本:
private int partition(int[] array, int startIndex, int endIndex)
{
int pivotIndex = getPivot(startIndex, endIndex);
swapElements(array, pivotIndex, endIndex);
pivotIndex = endIndex;
int store = startIndex;
for(int currentIndex = startIndex; (currentIndex <= endIndex - 1); currentIndex++)
{
if(array[currentIndex] <= array[pivotIndex])
{
swapElements(array, currentIndex, store);
store++;
}
}
swapElements(array, store, pivotIndex);
pivotIndex = store;
return pivotIndex;
}
store
变量的目的是什么?如果startIndex
和currentIndex
已经指向数组的第一个索引,为什么你需要store
做同样的事情?它在做什么?
为了回答你更简单的问题,你应该能够看到随着迭代的进行,store
与currentIndex
不一样。如果array[currentIndex] <= array[pivotIndex]
对于特定迭代为真,则仅递增。 - 所以store
通常会比currentIndex
小。
更具体地说,正在发生的事情是你在开头选择一个指向某个值的pivotIndex
。然后,您将在表中移动元素,以便小于pivotIndex
值的所有值都在数组中的该值之前,并且所有大于pivotIndex
值的值都在数组中的该值之后。 store
正在跟踪发现下一个值的位置,该值小于pivotIndex
值。该值移动到store
位置,然后store
递增以移过该值并表示应放置下一个较小值的位置。
在迭代结束时,store
的设计指向了枢轴值应该在哪里,因为store
之前的所有值都小于该值,并且store
之后的所有值都更大。所以最后,数据透视值移动到store
指向的位置,store
成为分区操作的最终索引,索引指向数据透视值