选择QuickSort的轴

时间:2017-09-24 09:31:40

标签: java pivot quicksort

我找到了代码。但我不明白它是如何工作的。 我知道pivot - 它的数组的中间元素。  但是这里的枢轴是int pivot = quickSortArray[p],其中,int i = 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++;
}

1 个答案:

答案 0 :(得分:0)

Pivot不一定是中间元素。它只是一个随机元素。代码修复了pivot,它总是第一个可能使代码更容易的元素。它不是最佳的,因为如果你有一个按降序排列的数组,它将需要O(n^2)而不是O(n log n)。最佳选择是随机选择一个元素。