簡體   English   中英

這是有效的quicksort實現嗎?

[英]Is this a valid quicksort implementation?

這是quicksort的有效實現嗎? 它與我在其他地方看到的實現方式不同,但是我發現以這種方式實現它比較容易。 據我所知,它仍然在原位,並且O(n log n)[編輯:O(n log n)預期運行時間,O(n ^ 2)最壞的情況],但要確保在我是在求職面試中做的,看起來像個白痴。

//Quicksort of arr between low and high
public static void myqs(int[] arr, int low, int high){
    if(arr == null){
        return;
    }

    if(low >= high){
        return;
    }

    //get pivot value, put it at the end of the chunk
    int pivotIndex = low + ((high - low) / 2);
    int pivot = arr[pivotIndex];
    swap(arr,pivotIndex,high);

    //move any lower number to the low end of chunk
    int lowIndex = low;
    for(int i = low; i < high; i++){
        if(arr[i] < pivot){
            swap(arr,lowIndex,i);
            lowIndex++;
        }
    }
    //move pivot value between low/high chunks
    swap(arr, lowIndex, high);

    //recurse on lower/upper halves
    myqs(arr, low, lowIndex - 1);
    myqs(arr, lowIndex + 1, high);
}

//swap values at indices i and j in arr
public static void swap(int[] arr, int i, int j){
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

看起來不錯(但您應該嘗試確定),但是它不在O(n log(n))

確實,可以通過始終將最大值作為中間值來發送將觸發n遞歸調用的特定數組,這將使總復雜度為N^2

例如: 1, 2, 3, 7, 4, 5, 6 7將成為樞軸,因此該數組將分為一個空數組和1, 2, 3, 4, 5, 6 在這種情況下,只有第一個拆分是“壞的”,但是您可以輕松地想象一個如何使所有拆分成為壞的。

為了獲得O(N log(N)) 平均復雜度,最流行的解決方案是隨機選擇樞軸。

暫無
暫無

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

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