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. 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:
swapcounter
global.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.