快速排序
1、快速排序的原理:在待排序n个记录任取一个记录,作为枢轴,设为pivotkey。经一趟排序,把小于pivotkey的关键字放在前面,大于pivotkey的关键字放在后面以pivotkey为界,然后对这两部分再重复上述的动作,直至每部分只有一个记录。
2、代码如下:
#include<iostream>
using namespace std;
int Partition(int a[],int low,int high);//功能:以a[low]为枢轴将a[]分割两半。
void QSort(int a[],int low,int high);
void QuickSort(int a[],int length);
int main()
{ int a[]={1,49,38,65,97,76,13,27,49};
for(int i=0;i<9;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
cout<<"After a quick sort.............."<<endl;
QuickSort(a,9);
for(int i=0;i<9;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
int Partition(int a[],int low,int high)
{
if(low>high||low<0)
{
return 0;
}
int pivotkey=a[low];//将枢轴记录放在pivotkey存储
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];
}
a[low]=pivotkey;//此时low==high;
return low;//返回枢轴记录的位置
}
void QSort(int a[],int low,int high)
{
if(low<high)
{
int pivotloc=Partition(a,low,high);
QSort(a,low,pivotloc-1);
QSort(a,pivotloc+1,high);
}
}
void QuickSort(int a[],int length)
{
QSort(a,0,length);
}
3、经编译的结果: