標籤:遞迴 partition 快速排序
快速排序的基本思想是:通過一趟排序將待排記錄分割成獨立的兩部分,其中一部分記錄的關鍵字均比另一部分記錄的關鍵字小,則可分別對這兩部分記錄繼續進行排序,已達到整個序列有序.
快速排序是一種不穩定的排序方法,其平均時間複雜度為:O(NlogN),最壞的情況是O(N*N)
特別注意:快速排序中用到的Partition函數,它的作用是進行一趟快速排序,返回“參考目標”的最終位置p,經過Partition處理之後,p左邊的記錄關鍵字均不大於參考目標,p右邊的記錄關鍵字均不小於參考目標。 Partition函數在找出數組中最大或最小的k個記錄也很有用.
C++代碼如下:
#include <iostream>#include <vector>#include <stack>using namespace std;template <typename Comparable>int partition(vector<Comparable> &vec,int low, int high){ Comparable pivot = vec[low]; while (low<high) { while (low<high && vec[high]>=pivot) { high--; } vec[low] = vec[high]; while (low <high&&vec[low]<=pivot) { low++; } vec[high] = vec[low]; } vec[low] = pivot; return low;}//使用遞迴快速排序template<typename Comparable>void quicksort1(vector<Comparable> &vec,int low ,int high){ if (low <high) { int mid = partition(vec, low, high); quicksort1(vec, low, mid - 1); quicksort1(vec, mid + 1, high); }}//其實就是用棧儲存每一個待排序子串的首尾元素下標,下一次while迴圈時取出這個範圍,對這段子序列進行partition操作,//每次得到的mid都是vector的最終位置,知道棧中不需要放入,也沒有資料時,迴圈結束template<typename Comparable>void quicksort2(vector<Comparable> &vec, int low, int high){ stack<int> st; if (low<high) { int mid = partition(vec, low, high); if (low<mid-1) { st.push(low); st.push(mid - 1); } if (mid+1<high) { st.push(mid + 1); st.push(high); } while (!st.empty()) { int q = st.top(); st.pop(); int p = st.top(); st.pop(); mid = partition(vec, p, q); if (p<mid-1) { st.push(p); st.push(mid - 1); } if (mid+1<q) { st.push(mid + 1); st.push(q); } } }}int _tmain(int argc, _TCHAR* argv[]){ int a[10] = { 12, 21, 33, 4, 50, 62, 71, 52,111,9 }; vector<int> vec(a, a + 10); int len = vec.size(); //quicksort1(vec, 0, len - 1); quicksort2(vec, 0, len - 1); for (int i=0; i < len;i++) { cout << vec[i]<< endl; } system("pause"); return 0;}
快速排序的遞迴和非遞迴實現 -----C++代碼實現