数据结构:严蔚敏、殷人昆快速排序规则不同的疑问
生活随笔
收集整理的這篇文章主要介紹了
数据结构:严蔚敏、殷人昆快速排序规则不同的疑问
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
快速排序
Partition 過程:將要排序的數據分成獨立的兩部分,其中一部分的所有數據都比另外一部分的所有數據都要小。快速排序整個排序過程可以遞歸進行,以此達到整個數據變成有序序列。
注:408原題中說,對所有尚未確定最終位置的所有元素進??遍處理稱為“?趟”排序,因此?次“劃分”≠?趟排序。因此,?次 Partition 可以確定?個元素的最終位置,??趟排序也許可以確定多個元素的最終位置。
需要注意的是,嚴蔚敏和殷人昆給出了兩種不同的快排方法。雖然兩種方法均正確,但排序中間步驟得到的序列不同,導致做題時對答案產生疑惑。本文對這兩種快排算法進行總結與對比。
嚴蔚敏《數據結構》P274
排序過程舉例:
以上述第一趟為例,快排的過程展示如下。先圈出最左邊的 49,把最左邊位置空出來,然后讓指針從最右邊的 49 開始往左走。
代碼
// 一趟快排 int Partition(SqList &L, int low, int high) {pivotkey = L[low]; //用字表的第一個記錄記錄樞軸的位置while (low < high) {while (low < high && L[high] > pivotkey) --high; //將比樞軸記錄小的記錄移到低端L[low] = L[high];while (low < high && L[low] < pivotkey) ++low;L[high] = L[low]; //將比樞軸記錄大的記錄移到高端}L[low] = pivotkey; //樞軸記錄到位return low; //返回樞軸位置 }// 快速排序算法 void Qsort(Sqlist &L, int low, int high) {if (low < high) { //長度大于1pivotloc = Partition(L, low, high); //將L一分為2QSort(L, low, pivotloc - 1); //對低子表遞歸排序,pivotloc是樞軸位置Qsort(L, pivotloc + 1, high); //對高子表遞歸排序} }殷人昆《數據結構》P406
排序過程舉例:
代碼
#include <iostream>#define LEN 9 using namespace std;void Print(int A[]) {for (int i = 0; i < LEN; i++) {cout << A[i] << " ";}cout << endl; }void Swap(int &a, int &b) {int tmp = a;a = b;b = tmp; }int Partition(int A[], int low, int high) {int pivotpos = low;int pivot = A[low];for (int i = low + 1; i < high + 1; ++i) {if (A[i] < pivot) {pivotpos++;if (pivotpos != i) {Swap(A[pivotpos], A[i]);}}}A[low] = A[pivotpos];A[pivotpos] = pivot;Print(A);return pivotpos; }void QuickSort(int A[], const int left, const int right) {if (left < right) {int privotpos = Partition(A, left, right);QuickSort(A, left, privotpos - 1);QuickSort(A, privotpos + 1, right);} }int main() {int A[] = {12, 2, 16, 30, 28, 10, 20, 6, 18}; //0~10QuickSort(A, 0, LEN - 1);return 0; }測試用例
示例 1
初始序列:
20, 4, 34, 5, 16, 33, 18, 29, 2, 40, 7每一次調用 Partition 的結果:
7 4 5 16 18 2 20 29 33 40 34 2 4 5 7 18 16 20 29 33 40 34 2 4 5 7 18 16 20 29 33 40 34 2 4 5 7 18 16 20 29 33 40 34 2 4 5 7 16 18 20 29 33 40 34 2 4 5 7 16 18 20 29 33 40 34 2 4 5 7 16 18 20 29 33 40 34 2 4 5 7 16 18 20 29 33 34 40示例 2
初始序列:
12, 2, 16, 30, 28, 10, 20, 6, 18每一次調用 Partition 的結果:
6 2 10 12 28 16 20 30 18 2 6 10 12 28 16 20 30 18 2 6 10 12 18 16 20 28 30 2 6 10 12 16 18 20 28 30總結
以上是生活随笔為你收集整理的数据结构:严蔚敏、殷人昆快速排序规则不同的疑问的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 操作系统:第三章 内存管理2 - 详解虚
- 下一篇: 面试必会系列 - 1.7 JVM 内存模