快速排序是比較排序中最快的一種排序(平均o(nlogn)),下面給出兩種遞歸的寫法 -> 區別主要在遞歸式 -> 即出去出口和遞歸調用的部分:
void quick_sort(int test[],int help[],int l,int r) //left、right
{ //test 爲目標排序數組,help 爲輔助數組(本例用int型數組舉例)
if(l >= r)
return;
int site = rand()%(r-l+1) + l;
int temp = test[site];
int p = l,q = r;
for(int i = l;i <= r;i++){
if(test[i] < temp) help[p++] = test[i];
if(test[i] > temp) help[q--] = test[i];
}
for(int i = l;i < p;i++) test[i] = help[i];
for(int i = r;i > q;i--) test[i] = help[i];
for(int i = p;i <= q;i++) test[i] = temp;
quick_sort(test,help,l,p-1);
quick_sort(test,help,q+1,r);
}
(PS:此做法是學洛谷網校課程時學到的,我略做修改。)
-
第二種:這種做法不需要輔助數組且速度很快,但不能避免判斷重複數組。
void quick_sort(int test[],int l,int r) //left、right { if(l >= r) return; std::swap(test[rand()%(r-l+1) + l],test[l]); int temp = test[l]; int i = l,j = r; while(i < j){ while(i < j&&test[j] > temp) j--; test[i] = test[j]; while(i < j&&test[i] <= temp) i++; test[j] = test[i]; } test[i] = temp; quick_sort(test,l,i-1); quick_sort(test,i+1,r); }
(PS:此做法爲《算法筆記》中所給,我自己略作修改)