快速排序:
分解:数组a[p..r]被划分为链两个(可能空)子数组a[p..q-1]和a[q+1..r],使得a[p..q-1]中的每个元素都小于等于a[q],而且,a[q]小于等于a[q+1,..r]中的元素。下表q的这个元素也在这个划分过程中进行计算。
解决:通过递归调用快速排序,对子数组a[p..q+1]和a[q+1..r]排序。
合并:因为两个子数组是就地排序的,将它们合并不需要操作,整个数组a[p..r]已排序。
/*************************************************************************/
/* this program just to show the QuickSort */
/* Author:SaoNian */
/* Time:2012/11/13 */
/*************************************************************************/
#include <time.h>
#include <stdlib.h>
#include <iomanip.h>
void quickSort(int *a,int start,int end);
int partition(int *a,int start,int end);
void showArray(int *a,int n);
int main()
{
int n;
cout<<"Please input the legnt of the Array:";
cin>>n;
srand((int)time(NULL));
int * a=new int[n];
for(int i=0;i<n;i++)
{
a[i]=rand()%n;
}
cout<<"the initial array:"<<endl;
showArray(a,n);
cout<<"now we sort it:"<<endl;
quickSort(a,0,n-1);
showArray(a,n);
return 0;
}
void showArray(int *a,int n)
{
for(int i=1;i<=n;i++)
{
cout<<setw(3)<<a[i-1];
if(i%10==0)
{
cout<<endl;
}
}
}
int partition(int *a,int start,int end)
{
int seed=a[start];//种子是start
int j=start;
int tmp;
for(int i=(start+1);i<=end;i++)//一次划分找到start的位置
{
if(a[i]<=seed)
{
j=j+1;
tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}
}
tmp=a[j];
a[j]=a[start];
a[start]=tmp;//交换最后一个比种子小和种子之间的位置
return j;
}
void quickSort(int *a,int start,int end)
{
if(start<end)
{
int pos=partition(a,start,end);
quickSort(a,start,pos-1);
quickSort(a,pos+1,end);
}
}