int partitions(int a[],int low,int high) {
int pivotkey=a[low];
while(low<high) {
while(low<high && a[high]>=pivotkey) --high;
a[low]=a[high];
while(low<high && a[low]<=pivotkey) ++low;
a[high]=a[low];}
a[low]=pivotkey;
return low; }
快速排序的递归算法
void quicksort(int a[],int low,int high)
{ int pivottag;
if(low<high) { //递归调用
pivottag=partitions(a,low,high);
quicksort(a,low,pivottag-1);
quicksort(a,pivottag+1,high); }
}
快速排序的俩种非递归算法
void QuickSort_Q(SqList &L){ 非递归(队列)
// 建立一个足够大的循环队列 //
InitQ(Q) ; InQ(Q , 1) ; InQ(Q , L.length);
while(!empty(Q)){
OutQ(Q , start); OutQ(Q , end );
i=partitions(L ,start , end );
if(start<i-1)
{ InQ(Q , start); InQ(Q , i-1 );}
if(end >i+1)
{ InQ(Q , i+1) ; InQ(Q , end );}
}
}
void QuickSort(SqList &L){ //非递归(栈)
InitStack(S); //建立 int 型动态栈作为辅存
push(S,1); push(S , L.length);
while(! Empty(S)){
pop(S,end) ; pop(S, start);
i=partitions(L , start , end );
//如果左右两边各有2个以上关键字,首、尾入栈
//
if( start <i-1 ) {push(S, start);push(S, i-1);}
if(end>i+1){push(S,i+1);push(S,end) ; }
}
}