注:本篇內容為翻譯,之所以選擇這篇進行翻譯原因是該文章含有動畫,能夠更加直觀地展示快速排序。同時,可以仔細看一下代碼,代碼中把結構化的思想給予了更加充分地表現。按照功能進行模塊划分的思想得到了徹底地貫徹。
以下內容翻譯自:
- http://cprogramminglanguage.net/quicksort-algorithm-c-source-code.aspx
譯文:
在快速排序算法中,使用了分治策略。首先把序列分成兩個子序列,遞歸地對子序列進行排序,直到整個序列排序結束。
步驟如下:
在序列中選擇一個關鍵元素做為軸;
對序列進行重新排序,將比軸小的元素移到軸的前邊,比軸大的元素移動到軸的后面。在進行划分之后,軸便在它最終的位置上;
遞歸地對兩個子序列進行重新排序:含有較小元素的子序列和含有較大元素的子序列。
下面的動畫展示了快速排序算法的工作原理。
快速排序圖示:可以圖中在每次的比較選取的key元素為序列最后的元素。
#include <stdio.h> #include <stdlib.h> void swap(int *x,int *y) { int temp; temp = *x; *x = *y; *y = temp; } int choose_pivot(int i,int j ) { return((i+j) /2); } void quicksort(int list[],int m,int n) { int key,i,j,k; if( m < n) { k = choose_pivot(m,n); swap(&list[m],&list[k]); key = list[m]; i = m+1; j = n; while(i <= j) { while((i <= n) && (list[i] <= key)) i++; while((j >= m) && (list[j] > key)) j--; if( i < j) swap(&list[i],&list[j]); } // 交換兩個元素的位置 swap(&list[m],&list[j]); // 遞歸地對較小的數據序列進行排序 quicksort(list,m,j-1); quicksort(list,j+1,n); } } void printlist(int list[],int n) { int i; for(i=0;i<n;i++) printf("%d\t",list[i]); } void main() { const int MAX_ELEMENTS = 10; int list[MAX_ELEMENTS]; int i = 0; // 產生填充序列的隨機數 for(i = 0; i < MAX_ELEMENTS; i++ ){ list[i] = rand(); } printf("進行排序之前的序列:\n"); printlist(list,MAX_ELEMENTS); // sort the list using quicksort quicksort(list,0,MAX_ELEMENTS-1); // print the result printf("使用快速排序算法進行排序之后的序列:\n"); printlist(list,MAX_ELEMENTS); }