快速排序法
操作
1.用Partition()函數(shù)取得劃分數(shù)轧苫,嚴的教材該數(shù)選的是數(shù)組第一個數(shù)下愈。
2.將小于劃分樹的左側放小于它的數(shù)汹碱,在右邊放比它大的數(shù)尖啡。此時劃分數(shù)的位置不需移動,就為它的排序完成后的位置停忿。
3.將劃分數(shù)的左側數(shù)組和右側數(shù)組分別迭代驾讲,直到左右數(shù)組為空或者為1。
代碼
劃分算法
//劃分區(qū)域返回劃分點的最終位置
public int Partition(int[] s,int low, int high)
{
//選數(shù)組的第一個點為劃分點
int pos=s[low];
while(low<high)
{
//劃分大于劃分點區(qū)域
while(s[high]>=pos&&low<high) --high;
s[low]=s[high];
//此時high可被覆蓋席赂,因為已被賦值到low中
while(s[low]<=pos&&low<high) ++low;
s[high]=s[low];
}
s[low]=pos;
return low;
}
返回值:low(為最終劃分數(shù)的位置)
迭代排序
//遞歸方式
public void RecursiveQSott(int[] s,int low,int high)
{
if(low<high)
{
int pivotpos=Partition(s,low,high);
//對小于部分區(qū)域排序
RecursiveQSott(s,low,pivotpos-1);
//對大于部分區(qū)域排序
RecursiveQSott(s,pivotpos+1,high);
}
}