快速排序的基本思想是:通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小,则可分别对这两部分记录继续进行排序,已达到整个 序列有序.
快速排序是一种不稳定的排序方法,其平均时间复杂度为:O(NlogN).
特别注意:快速排序中用到的Partition函数,它的作用是进行一趟快速排序,返回"曲轴“记录所在的位置p."曲轴“记录就是一个参考记录,经过Partition处理之后,p左边的记录关键字均不大于曲轴记录的关键字,p右边的记录关键字均不小于曲轴记录的关键字。 Partition函数在找出数组中最大或最小的k个记录也很有用.
快速排序的递归和非递归实现的代码余下:
-
- #include "stdafx.h"
- #include <iostream>
- #include <stack>
- using namespace std;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- void swap(int &a,int &b)
- {
- int temp=a;
- a=b;
- b=temp;
- }
-
-
- 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+=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);
- }
-
-
-
-
- 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);
-
- NonRecursiveQuickSort(a,len);
- printArray(a,len);
- system("PAUSE");
- return 0;
- }