快速排序的基本思想是:通過一趟排序將待排記錄分割成獨立的兩部分,其中一部分記錄的關鍵字均比另一部分記錄的關鍵字小,則可分別對這兩部分記錄繼續進行排序,已達到整個 序列有序.
快速排序是一種不穩定的排序方法,其平均時間複雜度為:O(NlogN).
特別注意:快速排序中用到的Partition函數,它的作用是進行一趟快速排序,返回"曲軸“記錄所在的位置p."曲軸“記錄就是一個參考記錄,經過Partition處理之後,p左邊的記錄關鍵字均不大於曲軸記錄的關鍵字,p右邊的記錄關鍵字均不小於曲軸記錄的關鍵字。 Partition函數在找出數組中最大或最小的k個記錄也很有用.
快速排序的遞迴和非遞迴實現的代碼餘下:
// 快速排序.cpp : 定義控制台應用程式的進入點。#include "stdafx.h"#include <iostream>#include <stack>using namespace std;/*//Partition實現方法1,嚴蔚敏版資料結構實現方法int Partition(int * a,int low,int high){ int pivotkey=a[low]; while(low<high) { while(low<high && a[high]>=pivotkey)--high;a[low]=a[high]; while(low<high && a[low]<=pivotkey)++low;a[high]=a[low]; } //此時low==high a[low]=pivotkey; return low;}*///交換a與b的值void swap(int &a,int &b){ int temp=a; a=b; b=temp;}//Partition實現方法2,演算法導論實現方法int Partition(int * a,int low,int high){ int pivotkey=a[high];//將最後一個元素當做曲軸 int p=low-1; for(int j=low;j<high;j++) { if(a[j]<=pivotkey){ p++;if(p!=j){ swap(a[p],a[j]);//在p前面的都是大於pivotkey的元素} //在p位置和其後的都是小於等於pivotkey的元素} } p+=1; swap(a[p],a[high]); return p;}void QSort(int *a,int start,int end){if(start<end){ int p=Partition(a,start,end); QSort(a,start,p-1); QSort(a,p+1,end);}}//遞迴形式的快速排序 void QuickSort(int *a,int len){ QSort(a,0,len-1);}//非遞迴方式實現快速排序//定義一個記錄待排序的區間[low,high]typedef struct Region{ int low; int high;}Region;void NonRecursiveQuickSort(int *a,int len){ stack<Region> regions;//定義一個棧變數 Region region; region.low=0; region.high=len-1; regions.push(region); while(!regions.empty()) { region=regions.top(); regions.pop(); int p=Partition(a,region.low,region.high); if(p-1>region.low) { Region regionlow; regionlow.low=region.low; regionlow.high=p-1; regions.push(regionlow); } if(p+1<region.high) { Region regionhigh; regionhigh.low=p+1; regionhigh.high=region.high; regions.push(regionhigh); } }}void printArray(int *a,int len){ for(int i=0;i<len;i++) cout<<a[i]<<" "; cout<<endl;}int _tmain(int argc, _TCHAR* argv[]){int a[]={49,38,65,97,76,13,27,49};int len=sizeof(a)/sizeof(int);printArray(a,len); //QuickSort(a,len);NonRecursiveQuickSort(a,len); printArray(a,len);system("PAUSE");return 0;}