从待排数组中选出一个数,将小于它的放到一边,大于它的放到另一边,再对这两边分别进行快速排序,持续递归,直到排序的只剩一个元素
时间复杂度O(nlogn)
单向扫描
#include<iostream>
using namespace std;
int partition(int *a,int l,int r)
{
int pivot=a[l];
int left=l+1;
int right=r;
while(left<=right)
{
if(a[left]<=pivot)
left++;
else
{
swap(a[left],a[right]);
right--;
}
}
swap(a[l],a[right]);
return right;
}
void QuickSort(int *a,int l,int r)
{
if(l<r)
{
int q=partition(a,l,r);
QuickSort(a,l,q-1);
QuickSort(a,q+1,r);
}
else
return;
}
int main()
{
int a[]={2,3,1,5,9,2,4,6,7,5,3,8,7,5,3,12};
int n=sizeof(a)/4;
QuickSort(a,0,n-1);
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}
双向扫描
#include<iostream>
using namespace std;
int partition(int *a,int l,int r)
{
int pivot=a[l];
int left=l+1;
int right=r;
while(left<=right)
{
while(left<=right&&a[left]<=pivot)
left++;
while(left<=right&&a[right]>pivot)
right--;
if(left<right)
swap(a[left],a[right]);
}
swap(a[l],a[right]);
return right;
}
void QuickSort(int *a,int l,int r)
{
if(l<r)
{
int q=partition(a,l,r);
QuickSort(a,l,q-1);
QuickSort(a,q+1,r);
}
else
return;
}
int main()
{
int a[]={2,3,1,5,9,2,4,6,7,5,3,8,7,5,3,12};
int n=sizeof(a)/4;
QuickSort(a,0,n-1);
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}
主元的选取不当可能造成程序运行时间增长,可以在左值,中值,右值中选取大小中间一个值作为主元
三分中值法优化
#include<iostream>
using namespace std;
int partition(int *a,int l,int r)
{
int midindex=l+(r-l)/2;
int midvalueindex=0;
if(a[l]<=a[midindex]&&a[l]>=a[r]||a[l]>=a[midindex]&&a[l]<=a[r])
midvalueindex=l;
else if(a[r]<=a[midindex]&&a[r]>=a[l]||a[r]>=a[midindex]&&a[r]<=a[l])
midvalueindex=r;
else
midvalueindex=midindex;
swap(a[l],a[midvalueindex]);
int pivot=a[l];
int left=l+1;
int right=r;
while(left<=right)
{
while(left<=right&&a[left]<=pivot)
left++;
while(left<=right&&a[right]>pivot)
right--;
if(left<right)
swap(a[left],a[right]);
}
swap(a[l],a[right]);
return right;
}
void QuickSort(int *a,int l,int r)
{
if(l<r)
{
int q=partition(a,l,r);
QuickSort(a,l,q-1);
QuickSort(a,q+1,r);
}
else
return;
}
int main()
{
int a[]={2,3,1,5,9,2,4,6,7,5,3,8,7,5,3,12};
int n=sizeof(a)/4;
QuickSort(a,0,n-1);
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}