1、快速排序思想:选取基准元素,将数组分成两个子数组,其中一个数组里面的元素都比基准元素大,而另一个数组元素都比基准元素小。然后递归调用快速排序对这两个子数组进行排序。
代码:
//快速排序 //输入数组a,数组起始位置start(初始值0),结束位置end(初始值n-1) void QuickSort(int *a,int start,int end) { int i=start,j=end+1; int x=a[i],temp; //起始位置元素作为基准元素 //划分子数组 do{ do { i++; } while (a[i]<x); do { j--; } while (a[j]>x); if (i<j) { temp=a[i]; a[i]=a[j]; a[j]=temp; } }while(i<j); a[start]=a[j]; a[j]=x; //递归调用快速排序 if(j-1>start) QuickSort(a,start,j-1); if(j+1<end) QuickSort(a,j+1,end); }
2、改进的快速排序
一般快速排序始终取每一个子数组中一个固定的元素作为基准元素,这个基准元素不一定是最佳的。为了保证每个元素都有机会被选作基准元素,所以在改进的快速排序版本中,我们加入随机化的成分,从子数组中随机选择一个元素作为基准元素,然后在进行子数组分割以及递归调用。
代码如下:
#include "stdafx.h" #include "iostream.h" #include "string.h" #include <time.h> #include <stdlib.h> //加入随机化的快速排序 //输入数组a,数组起始位置start(初始值0),结束位置end(初始值n-1) void QuickSort(int *a,int start,int end) { int i=start,j=end+1,temp; //随机选取基准元素 int r=(int)(rand()%1000/1000.0*(end-start))+start; temp=a[i]; a[i]=a[r]; a[r]=temp; int x=a[i]; //起始位置元素作为基准元素 //划分子数组 do{ do { i++; } while (a[i]<x); do { j--; } while (a[j]>x); if (i<j) { temp=a[i]; a[i]=a[j]; a[j]=temp; } }while(i<j); a[start]=a[j]; a[j]=x; //递归调用快速排序 if(j-1>start) QuickSort(a,start,j-1); if(j+1<end) QuickSort(a,j+1,end); } int main(int argc, char* argv[]) { int a[]={0,23,5,35,32,435,42,75,24,24,12,64,53,31,97,75,324,75,86,9,54,24,235}; int len=sizeof(a)/sizeof(int); QuickSort(a,0,len-1); for (int i=0;i<len;i++) { cout<<a[i]<<" "; } cout<<endl; return 0; }