递归快速排序,计数交换和比较问题

时间:2015-04-29 12:19:28

标签: c arrays recursion quicksort bubble-sort

我想比较一下,使用bubblesort与quicksort函数对一组唯一数字进行排序所需的交换和比较(<,>,==,!=)。问题是我使用的quicksort函数是递归的,我有点不确定如何跟踪交换比较。试图使用指针来跟踪计数,但没有成功。有谁可以帮助我?

my bubblesort:

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);

    }
}

1 个答案:

答案 0 :(得分:3)

使用评论中建议的全局变量:

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#;