【发布时间】:2015-07-08 17:30:20
【问题描述】:
我想比较一下气泡排序与快速排序函数对一组唯一数字进行排序所需的交换和比较次数(、==、!=)。问题是我使用的快速排序函数是递归的,我有点不确定如何跟踪交换比较。尝试使用指针来跟踪计数但未成功。谁能帮帮我?
我的冒泡排序:
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);
}
}
【问题讨论】:
-
你能详细说明你用指针尝试了什么吗?也许提供代码?
-
你能让你的计数器成为一个全局变量吗?
-
感谢您的快速回复,但我们设法解决了问题。
标签: c arrays recursion quicksort bubble-sort