Java 为快速排序选择轴

Java 为快速排序选择轴,java,pivot,quicksort,Java,Pivot,Quicksort,我找到密码了。但我不明白它是怎么工作的。 正如我所知,pivot是数组的中间元素。 但是这里的pivot是intpivot=quickSortArray[p]其中,inti=p,所以p=0和0它不是数组的中间,可以解释一下吗 public int partition(int p, int q) { int i = p; int j = q + 1; // Get the pivot element from the middle of the list int

我找到密码了。但我不明白它是怎么工作的。 正如我所知,pivot是数组的中间元素。 但是这里的pivot是
intpivot=quickSortArray[p]
其中,inti=p,所以p=0和0它不是数组的中间,可以解释一下吗

 public int partition(int p, int q) {
    int i = p;
    int j = q + 1;
    // Get the pivot element from the middle of the list
    int pivot = quickSortArray[p];
    // Divide into two lists
    do {
        // If the current value from the left list is smaller then the pivot
        // element then get the next element from the left list
        do {
            i++;// As we not get we can increase i
        } while (quickSortArray[i] < pivot && i<q);
        // If the current value from the right list is larger then the pivot
        // element then get the next element from the right list
        do {
            j--;// As we not get we can increase j
        } while (quickSortArray[j] > pivot);
        // If we have found a values in the left list which is larger then
        // the pivot element and if we have found a value in the right list
        // which is smaller then the pivot element then we exchange the
        // values.
        if (i < j) {
            swap(i, j);
        }

    } while (i < j);
    // swap the pivot element and j th element
    swap(p, j);
    quickSortComparisons++;
    return j;

}

private void swap(int p, int j) {
    // exchange the elements
    int temp = quickSortArray[p];
    quickSortArray[p] = quickSortArray[j];
    quickSortArray[j] = temp;
    quickSortSwaps++;
}

public void quicksort() {
    // Recursion
    quicksort(0, quickSortCounter - 1);
}

public void quicksort(int p, int q) {
    int j;
    if (p < q) {
        // Divide into two lists
        j = partition(p, q);
        // Recursion
        quicksort(p, j - 1);
        quicksort(j + 1, q);
    }
    quickSortComparisons++;
}
公共int分区(int p,int q){
int i=p;
int j=q+1;
//从列表中间获取pivot元素
int pivot=quickSortArray[p];
//分为两个列表
做{
//如果左侧列表中的当前值较小,则轴
//元素,然后从左侧列表中获取下一个元素
做{
i++;//当我们没有得到时,我们可以增加i
}while(QuickPortArray[i]
枢轴不必是中间元素。它必须是一个随机元素。代码将轴心点固定为第一个元素,这可能会使代码更简单。它不是最优的,因为如果数组按降序排序,则需要
O(n^2)
而不是
O(n logn)
。最好是随机选取一个元素。

欢迎使用堆栈溢出!看起来您需要学习使用调试器。请随便吃点。如果您以后仍然有问题,请随时回来提出更具体的问题。