您的位置:首页 > 其它

算法导论习题7-4—快排中堆栈深度的优化

2012-07-02 20:01 441 查看
//Quick_sort
//timecomplexityisnlgn
//thewayisfindanelement,andpartitionthearrayaccordingtothiselement

#include<iostream>
usingnamespacestd;
intPartition(inta[],intp,intr)
{
intnum=a[r];
inti=p-1;
intj,temp;
//partitionthearrayaccordingtonum
for(j=p;j<=r-1;j++)
{
if(a[j]<num)
{
i+=1;
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
//Insertthenumbetweenthepartion
temp=a[r];
a[r]=a[i+1];
a[i+1]=temp;
//returnthepartitionboundray
returni+1;
}
//RandomizedPartition,inthisfunctionwerandomselect
//theelementinarray,andexchangeitwiththelaseelementinarray
//thetargetislowdowntheaveragetimecomplexity!
intRandomizedPartition(inta[],intp,intr)
{
//generateibetweenpandr
inti=rand()%(r+1-p)+p;
inttemp;
temp=a[i];
a[i]=a[r];
a[r]=temp;
returnPartition(a,p,r);
}
//recursivecallsQuickSorttocpmplatethesort
voidQuickSort(inta[],intp,intr)
{
intq;
if(p<r)
{
q=RandomizedPartition(a,p,r);
QuickSort(a,p,q-1);
QuickSort(a,q+1,r);
}
}
//tailrecursiveQuickSort
//thedeapthoftheheapduetotherunofrecursiveQuickSortislgn
//直觉上每次partition如果都能对半划分,则递归的堆栈深度为lgn
//但是这种情况为理想状态,我们可以每次都挑出划分的子数组中较短的进行递归的QuickSort
//剩下的另一半用循环来处理。
voidTRQuickSort(inta[],intp,intr)
{
intq;
while(p<r)
{
q=RandomizedPartition(a,p,r);
if((q-p)<(r-q))
{
TRQuickSort(a,p,q-1);
p=q+1;
}
else
{
TRQuickSort(a,q+1,r);
r=q-1;
}
}
}
intmain()
{
intarr[10]={5,2,3,6,1,7,6,9,5,10};
TRQuickSort(arr,0,9);
inti;
for(i=0;i<10;i++)
{
cout<<arr[i]<<"";
}
cout<<endl;
return0;
}




优化的尾递归使得快速排序的堆栈深度为lgn。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: