简体   繁体   English

快速排序中的掉期和比较

[英]Swaps and Comparisons in Quicksort

I think I have managed to figure the comparisons but I am trying to figure out how can I count the numbers of swaps. 我认为我已经设法比较了,但是我试图弄清楚如何计算掉期数。 I have a problem with the value of swapcounter and the recursion. 我对swapcounter和递归的值有swapcounter Any ideas? 有任何想法吗?

int quicksort (int nums[],int n,int left,int right){//quicksort takes an array, the leftmost index and the rightmost index

    int swapCounter=0;
    int i=left,j=right,temp;
    int comparisonCounter = 0;
    int pivot = nums[(left + right) / 2];
/* partition */
    while(i<=j){
    comparisonCounter++;
        while(nums[i]<=pivot)
            i++;
        while(nums[j]>pivot)
            j--;
        if(i<=j){
            temp=nums[i];
            nums[i]=nums[j];
            nums[j]=temp;
            i++;
            j--;
            swapCounter++;
        }
    }  

    /* recursion */
    if (left < j)
        comparisonCounter+=quicksort(nums,n, left, j);
    if (i < right)
        comparisonCounter+=quicksort(nums,n, i, right);

    printf("\nSwaps=%d\n",swapCounter);
    return comparisonCounter;
    }

You can: 您可以:

  • Make swapcounter global. swapcounter全局。
  • Make the function take a pointer to the variable. 使函数采用指向变量的指针。
  • Make the function call another function to do the counting, thus making maintaining the counter state Someone Else's problem. 使该函数调用另一个函数进行计数,从而使计数器状态保持其他人的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM