簡體   English   中英

如何在Quicksort算法中實現遞歸?

[英]How can I implement the recursion in my Quicksort algorithm?

我正在嘗試在Java中實現quicksort,以學習基本算法。 我了解算法的工作原理(並且可以在紙上完成),但是發現很難用代碼編寫它。 我設法完成了以下步驟:將所有元素都比左側的樞軸小,而將右側的樞軸大(請參見下面的代碼)。 但是,我無法弄清楚如何實現算法的遞歸部分,因此需要對左​​側和右側進行遞歸排序。 有什么幫助嗎?

public void int(A, p, q){
    if(A.length == 0){ return; }
    int pivot = A[q];
    j = 0; k = 0;
    for(int i = 0; i < A.length; i++){
        if(A[i] <= pivot){
            A[j] = A[i]; j++;
        }
        else{
            A[k] = A[i]; k++;
        }
    }
    A[j] = pivot;
}

大免責聲明 :我沒有編寫這段代碼,因此不需要投票。 但我鏈接到詳細解釋quicksort的教程。 也為我提供了急需的算法更新! 給出的示例有很好的注釋,也許可以幫助您繞開它。

我建議您將其適應您的代碼並為其編寫som測試以驗證其是否有效

Quicksort是一種快速的,遞歸的,非穩定的排序算法,它按照分而治之的原理工作。 在最佳情況下,Quicksort會將陣列分為幾乎兩個相同的部分。 如果數組包含n個元素,則第一次運行將需要O(n)。 排序其余的兩個子數組需要2 O(n / 2)。 最終得到O(n log n)的性能。 在最壞的情況下,快速排序在每次迭代中僅選擇一個元素。 因此,它是O(n)+ O(n-1)+(On-2).. O(1)等於O(n ^ 2)。*

public class Quicksort  {
private int[] numbers;
private int number;

public void sort(int[] values) {
    // check for empty or null array
    if (values ==null || values.length==0){
        return;
    }
    this.numbers = values;
    number = values.length;
    quicksort(0, number - 1);
}

private void quicksort(int low, int high) {
    int i = low, j = high;
    // Get the pivot element from the middle of the list
    int pivot = numbers[low + (high-low)/2];

    // Divide into two lists
    while (i <= j) {
        // If the current value from the left list is smaller than the pivot
        // element then get the next element from the left list
        while (numbers[i] < pivot) {
            i++;
        }
        // If the current value from the right list is larger than the pivot
        // element then get the next element from the right list
        while (numbers[j] > pivot) {
            j--;
        }

        // If we have found a value in the left list which is larger than
        // the pivot element and if we have found a value in the right list
        // which is smaller than the pivot element then we exchange the
        // values.
        // As we are done we can increase i and j
        if (i <= j) {
            exchange(i, j);
            i++;
            j--;
        }
    }
    // This is the recursion part you had trouble with i guess?
    // Recursion
    if (low < j)
        quicksort(low, j);
    if (i < high)
        quicksort(i, high);
}

private void exchange(int i, int j) {
    int temp = numbers[i];
    numbers[i] = numbers[j];
    numbers[j] = temp;
}
}

鏈接到教程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM