1、算法导论描述
参见《算法导论》对快速排序的伪代码描述:
关键代码:
模拟过程表示:
2、C++实现
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 5 #define DATA_LEN 20 6 7 void PrintData(int data[], int start_index, int end_index) { 8 printf("DATA[%d, %d]:", start_index, end_index); 9 for (int i = 0; i < DATA_LEN; ++i) { 10 printf("%d ", data[i]); 11 } 12 printf("\n"); 13 } 14 15 void Swap(int szData[], int i, int j) { 16 printf("[%d] %d <-> [%d] %d\n", i, szData[i], j, szData[j]); 17 int temp = szData[i]; 18 szData[i] = szData[j]; 19 szData[j] = temp; 20 } 21 22 int Partition(int szData[], int startIndex, int endIndex) { 23 PrintData(szData, startIndex, endIndex); 24 int guard = szData[endIndex]; 25 int i = startIndex - 1; 26 int j = startIndex; 27 for (; j < endIndex; ++j) { 28 if (szData[j] <= guard) { 29 ++i; 30 Swap(szData, i, j); 31 } 32 } 33 34 Swap(szData, endIndex, i + 1); 35 return i + 1; 36 } 37 38 void QuickSort(int szData[], int startIndex, int endIndex) { 39 if (startIndex < endIndex) { 40 int j = Partition(szData, startIndex, endIndex); 41 QuickSort(szData, startIndex, j - 1); 42 QuickSort(szData, j + 1, endIndex); 43 } 44 } 45 46 int main() 47 { 48 srand((unsigned)time(NULL)); 49 50 int origin_data[DATA_LEN] = { 0 }; 51 printf("ORIGIN:"); 52 for (int i = 0; i < DATA_LEN; ++i) { 53 origin_data[i] = rand() % 100; 54 printf("%d ", origin_data[i]); 55 } 56 printf("\n"); 57 58 QuickSort(origin_data, 0, DATA_LEN - 1); 59 60 printf("SORTED:"); 61 for (int i = 0; i < DATA_LEN; ++i) { 62 printf("%d ", origin_data[i]); 63 } 64 printf("\n"); 65 66 system("pause"); 67 return 0; 68 }
3、心得
单游标一趟遍历,i总指向的是最后一个小于“卫兵”的值所在位置,j不断正向遍历至“卫兵”(最后元素)的倒数第二个。最后交换i+1与“卫兵”就对了!