簡體   English   中英

遞歸快速排序,計數交換和比較問題

[英]recursive quicksort, count swap and comparison issue

我想比較Bubblesort與quicksort函數對唯一數字數組進行排序所花費的交換次數和比較次數(<,>,==,!=)。 問題是我使用的quicksort函數是遞歸的,我有點不確定如何跟蹤交換比較。 嘗試使用指針來跟蹤計數,但未成功。 有人可以幫我嗎?

我的泡泡排序:

void bubble_sort(int arr[], int max)
{
    int i=0, j, temp, flag;
    int swap=0, comp=0;
    while(1)
    {
        flag = 0;
        for (j = 0 && comp++;  j < max - i - 1; j++)
        {
            comp++;
            if (arr[j] > arr[j+1])
            {
                swap++;
                /* Swapping */

                temp     = arr[j];
                arr[j]   = arr[j+1];
                arr[j+1] = temp;
                flag=1;
            }
        }
        i++;
        comp++;
        if (flag == 0)
        {
            printf("number of swaps: %d\n",swap);
            printf("number of comparisons: %d \n\n",comp);
            break;
        }
    }
}

我的快速排序:

void quicksort(int arr[],int first,int last)
{
    int pivot,j,temp,i;

    if(first<last)
    {
        pivot=first;
        i=first;
        j=last;

        while(i<j)
        {
            while(arr[i]<=arr[pivot]&&i<last)
                i++;
            while(arr[j]>arr[pivot])
                j--;
            if(i<j)
            {
                temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }

        temp=arr[pivot];
        arr[pivot]=arr[j];
        arr[j]=temp;
        quicksort(arr,first,j-1);
        quicksort(arr,j+1,last);

    }
}

解:

void quick_sort(int arr[],int first,int last, int *swap, int *comp)
{
    int pivot,j,temp,i;
    if(++(*comp) && first<last)
    {
        pivot=first;
        i=first;
        j=last;

        while(++(*comp) && i<j)
        {
            while(++(*comp) && arr[i]<=arr[pivot]&&i<last)
                i++;
            while(++(*comp) && arr[j]>arr[pivot])
                j--;
            if(++(*comp) && i<j)
            {
                ++(*swap);
                temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }
        ++(*swap);
        temp=arr[pivot];
        arr[pivot]=arr[j];
        arr[j]=temp;
        quick_sort(arr,first,j-1, swap, comp);
        quick_sort(arr,j+1,last, swap, comp);

    }
}

使用注釋中建議的全局變量:

int _SwapCount = 0;
void quicksort(int arr[],int first,int last)
{
   ...
   //whenever you swap
   _SwapCount++;

或將指向int的指針作為參數:

void quicksort(int arr[],int first,int last, int* swapCount)
{
   ...
   //whenever you swap
   (*swapCount)++;
   //recursion
   quicksort(arr,first,j-1, swapCount);
   ...

並在頂級快速排序完成后輸出swapCount。

編輯:最初將標簽誤讀為c#;

暫無
暫無

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

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