C 递归快速排序、计数交换和比较问题
我想比较一下bubblesort和quicksort函数对一个唯一数字数组进行排序需要多少交换和比较(,=,!=)。问题是我使用的快速排序函数是递归的,我有点不确定如何跟踪交换比较。试图使用指针跟踪计数,但未成功。有人能帮我吗 我的泡泡糖:C 递归快速排序、计数交换和比较问题,c,arrays,recursion,quicksort,bubble-sort,C,Arrays,Recursion,Quicksort,Bubble Sort,我想比较一下bubblesort和quicksort函数对一个唯一数字数组进行排序需要多少交换和比较(,=,!=)。问题是我使用的快速排序函数是递归的,我有点不确定如何跟踪交换比较。试图使用指针跟踪计数,但未成功。有人能帮我吗 我的泡泡糖: void bubble_sort(int arr[], int max) { int i=0, j, temp, flag; int swap=0, comp=0; while(1) { flag = 0;
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 bubble_排序(int arr[],int max)
{
int i=0,j,温度,标志;
整数交换=0,补偿=0;
而(1)
{
flag=0;
对于(j=0&&comp++;jarr[j+1])
{
swap++;
/*交换*/
温度=arr[j];
arr[j]=arr[j+1];
arr[j+1]=温度;
flag=1;
}
}
i++;
comp++;
如果(标志==0)
{
printf(“交换数量:%d\n”,交换);
printf(“比较次数:%d\n\n”,comp);
打破
}
}
}
我的快速排序:
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快速排序(int-arr[],int-first,int-last)
{
内枢轴,j,温度,i;
如果(首先使用注释中建议的全局变量:
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#或者使用注释中建议的全局变量:
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#你能详细说明你用指针做了什么吗?也许提供代码?你能把你的计数器变成一个全局变量吗?谢谢你的快速回复,但我们设法解决了这个问题。你能详细说明你用指针做了什么吗?也许提供代码?你能把你的计数器变成一个全局变量吗变量?感谢您的快速回复,但我们设法解决了问题。我同意全局变量是可行的选项。第二个选项将有编译时错误,因为int&
不是数据类型。我同意全局变量是可行的选项。第二个选项将有编译时错误,因为int&
不是数据类型.