快速排序
来源:互联网 发布:棋牌游戏源码可控制 编辑:程序博客网 时间:2024/04/28 05:00
快速排序是由C.A.R.Hoare在1960年发明一种基于分治模式的递归算法。它的工作方式是,将数组划分为两组,然后独立排序各个部分。
下面是对一个典型子数组A[p..r]排序的分治过程的三个步骤:
分解:数组A[p..r]被划分成两个(可能空)子数组A[p..q-1]和A[q+1..r],使得A[p..q-1]中的每个元素都小于等于A[q],而且,小于等于A[q+1..r]中的元素。下标q也在这个划分过程中进行计算。
解决:通过递归调用快速排序,对子数组A[p..q-1]和A[q+1..r]排序。
合并:因为两个子数组是就地排序的,将它们的合并不需要操作:整个数组A[p..r]已排序。
下面的过程实现快速排序:
QUICKSORT(A,p,r)
1 if p<r
2 then q=PARTITION(A,p,r)
3 QUICKSORT(A,p,q-1)
4 QUICKSORT(A,q+1,r)
为排序一个完整的数组A,最初的调用是QUICKSORT(A,1,length(A))。
快速排序算法的关键是PARTITION过程,它对子数组A[p..r]进行就地重排:
PARTITION(A,p,r)
1 x=A[r]
2 i=p-1
3 for j=p to r-1
4 do if A[j]<=x
5 then i=i+1
6 exchange A[i] with A[j]
7 exchange A[i+1] with A[r]
8 return i+1
实例:
#include <iostream>#include <cstdlib> #include <ctime>using namespace std;void exch(int *a,int *b){int t=*a;*a=*b;*b=t;}int Partition(int* a,int p,int r){int x,i,j;x=a[r];i=p-1;for(j=p;j<r;++j){if(a[j]<=x){++i;exch(&a[i],&a[j]);}}++i;exch(&a[i],&a[r]);return i;}void quicksort(int* a,int p,int r){int q;if(p<r){q=Partition(a,p,r);quicksort(a,p,q-1);quicksort(a,q+1,r);}}int main(){int a[100];int len=sizeof(a)/sizeof(sizeof(a[0]));for(int i=0;i<len;i++) a[i]=rand(); clock_t start = clock();quicksort(a,0,len-1); // len-1clock_t end =clock();for(int i=0;i<len;i++) cout<<a[i]<<endl;//计算quicksort所用时间 //cout<<"Elapsed time:"<<difftime(end,start)<<"msec.\n"; system("pause"); return 0;}