非递归:
#include<iostream>
#include<stack>
using namespace std;
int partition(int*a,int low,int high)
{
int mid=(low+high)/2;
if(a[low]>a[high])
swap(a[low],a[high]);
if(a[mid]>a[high])
swap(a[mid],a[high]);
if(a[mid]>a[low])
swap(a[low],a[mid]);
int pivot=a[low];
while(low<high)
{
while(low<high && a[high]>=pivot)
high--;
a[low]=a[high];
while(low<high && a[low]<=pivot)
low++;
a[high]=a[low];
}
a[low]=pivot;
return low;
}
void Qsort(int*a,int left,int right)
{
stack<int> s;
s.push(left);
s.push(right);
while(!s.empty())
{
int right=s.top();s.pop();
int left=s.top();s.pop();
int pivot=partition(a,left,right);
if(pivot-1>left)
{
s.push(left);
s.push(pivot-1);
}
if(pivot+1<right)
{
s.push(pivot+1);
s.push(right);
}
}
}
int main()
{
int a[10]={10,25,8,18,22,4,12,1};
Qsort(a,0,7);
return 0;
}
递归:
#include<iostream>
using namespace std;
int partition(int *a,int low,int high)
{
int mid=(low+high)/2;
if(a[low]>a[high])
swap(a[low],a[high]);
if(a[mid]>a[high])
swap(a[mid],a[high]);
if(a[mid]>a[low])
swap(a[low],a[mid]);
int pivot=a[low];
while(low<high)
{
while(low<high && a[high]>=pivot)
high--;
a[low]=a[high];
while(low<high && a[low]<=pivot)
low++;
a[high]=a[low];
}
a[low]=pivot;
return low;
}
void Qsort(int *a,int low,int high)
{
if(low<high)
{
int pivot=partition(a,low,high);
Qsort(a,low,pivot-1);
Qsort(a,pivot+1,high);
}
}
int main()
{
int a[10]={10,25,8,18,22,4,12,1};
Qsort(a,0,7);
return 0;
}