【发布时间】:2014-12-30 05:21:51
【问题描述】:
我想我知道快速排序算法。但我需要帮助找出最坏的情况。
让我们看看下面的快速排序代码---->
void quicksort(int arr[],int low,int high) //low and high are pased from main()
{
int m;
if(low<high)
{
m=partition(arr,low,high);
quicksort(arr,low,m-1);
quicksort(arr,m+1,high);
}
}
int partition(int arr[],int low,int high)
{
int pivot=arr[low],i=low,j=high;
while(i<j)
{
while((arr[i]<=pivot)&&(i<=high))
i++;
while(arr[j]>pivot)
j--;
if(i<j)
swap(arr,i,j); //swaps arr[i]and arr[j]
}
swap(arr,low,j); //swaps arr[low] and arr[j]
return j;
}
这里不写swap函数的定义,因为它是不言自明的。
现在让我们跟踪 arr 1 2 3 4 5 的上述代码
0 4 0 partion swaps 1 with 1 and returns 0 which is assigned to m
low high m
__________________________
0 0 *
0 4 0
low high m
___________________________
0 0 *
1 4 1 partition swaps 2 with 2
0 4 0
low high m
____________________________
2 4 2 partition swaps 3 with 3
1 4 1
0 4 0
low high m
____________________________
2 1 *
2 4 2
1 4 1
0 4 0
low high m
______________________________
3 4 3 partition swaps 4 with 4
2 4 2
1 4 1
0 4 0
low high m
________________________________
3 2 *
3 4 3
2 4 2
1 4 1
0 4 0
low high m
_________________________________
4 4 *
3 4 3
2 4 2
1 4 1
0 4 0
low high m
_________________________________
Stack empty
low high m
问题1.我对快速排序的理解正确吗?
ques2.在最坏的情况下,快速排序进行 n-1+n-2+.....+1 次比较。如何?
在这里,我认为它会有 n+2 比较...而不是 n-1。 分区会检查
(1<=1,i++),(5>1,j--),
(2<=1,don't incr i),(4>1,j--),
(3>1,j--),
(2>1,j--),
(1>1,don't incr j)
总共 7 次,即 (n+2) 次比较
【问题讨论】: