簡體   English   中英

快速排序的一個特例 pivot

[英]A peculiar case of quicksort pivot

我在 C 中實現了快速排序,它運行得很好。 然后我開始玩 pivot 元素,現在我陷入了一個奇怪的境地。 我所實現的有時運行良好,但在其他所有時間都不運行(不顯示輸出),我無法查明為什么會發生這種情況。 這是我的代碼。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


void swap(int *x, int* y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}

void displayArray(int arr[], size_t size)
{
    for(int i = 0; i < size; ++i)
        printf("%d\t",arr[i]);
    printf("\n");
}

unsigned int getNMinNMax(int arr[], unsigned int lb, unsigned int ub)
{
    unsigned int a = rand()%(ub-lb +1) + lb, b =rand()%(ub-lb +1) + lb,c = rand()%(ub-lb +1) + lb;
    // printf("%d %d %d \n", a,b,c);
    // getchar();
    // inefficient comparisons incoming, brace yourselves
    if(arr[a] >= arr[b] && arr[a] < arr[c]) return a;
    else if(arr[b] >= arr[a] && arr[b] < arr[c]) return b;
    else return c;
}

unsigned int partition(int arr[], unsigned int lb, unsigned int ub)
{
    // pivot selection mania(select necessarily from array elements)****{needs more testing}
    // 1)middle element
    // swap(&arr[lb + (ub - lb)/2], &arr[lb]);
    // 2)neither smallest nor largest
    // swap(&arr[getNMinNMax(arr,lb,ub)], &arr[lb]); (problem here)
    // 3)random
    // swap(&arr[rand()%(ub-lb +1) + lb], &arr[lb]); (problem here)
    // 4)1st element(no optimisation)
    int pivot = arr[lb];
    unsigned int down = lb + 1, up = ub;
    while(down <= up)
    {
        while(arr[down] <= pivot)
            down++;
        while(arr[up] > pivot)
            up--;
        if(down < up)
            swap(&arr[down], &arr[up]);
    }
    arr[lb] = arr[up];
    arr[up] = pivot;
    return up;
}

void quickSort(int arr[], unsigned int lb, unsigned int ub)
{
    while(lb < ub)
    {
        unsigned int pivot = partition(arr, lb, ub);
        if (pivot - lb < ub - pivot)
        {
            quickSort(arr, lb, pivot - 1);
            lb = pivot + 1;
        }
        else
        {
            quickSort(arr, pivot + 1, ub);
            ub = pivot - 1;
        }
    }
}

int main()
{
    int arr[] = {1,2,3,5,0,-1,-2,-3};
    srand(time(NULL));
    quickSort(arr, 0, sizeof(arr)/sizeof(int)-1);
    displayArray(arr,sizeof(arr)/sizeof(int));
    return 0;
}

我已經評論了哪些行導致 output 消失。 我很確定我的實施在其他情況下有效,因為我在這些情況下沒有遇到 output disappearacne,但請隨時指出任何其他錯誤。 我使用的編譯器是 Onlinegdb C 編譯器(afaik 是 gcc)。

PS:我已經添加了我的完整代碼,因為我發現當我弄亂我的分區 function 時,我的顯示器 function 無法正常工作很奇怪。我也嘗試調試它但沒有運氣。

問題是由以下原因引起的:

while(lb < ub)

通過pivot的調整, ub可以達到-1,但是ub的類型是unsigned int,所以ub看起來是一個很大的正數,while循環會繼續下去。

將此行更改為:

while( (int)lb < (int)ub )

允許程序完成並顯示排序后的數組。

暫無
暫無

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

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