#include<iostream>
using namespace std;
int Partion(int *a, int l, int h)
{
int p = a[l];
while (l<h)
{
while (l<h && a[h]>=p)
h--;
a[l] = a[h];
a[h] = p;
while (l<h && a[l]<=p)
l++;
a[h] = a[l];
a[l] = p;
}
return l;
}
/* 递归法
void quick_sort(int *a, int low, int high)
{
if (low>=high)
return;
int q = Partion(a,low,high);
quick_sort(a,low,q-1);
quick_sort(a,q+1,high);
}*/
// 非递归法
void quick_sort(int *a, int l ,int h)
{
if (l>=h)
return;
int *s = new int[h];
int low, high, q, p = 0;
//进栈
s[p++] = l;
s[p++] = h;
while (p>0)
{
//出栈
high = s[--p];
low = s[--p];
if (low<high)
{
q = Partion(a,low,high);
// 较长的一段入栈
if (q-low > high-q)
{
s[p++] = low;
s[p++] = q-1;
if (high>q)
{
s[p++] = q+1;
s[p++] = high;
}
}else{
s[p++] = q+1;
s[p++] = high;
if (q>low)
{
s[p++] = low;
s[p++] = q-1;
}
}
}
}
}
void main(){
int a[] = {3,2,4,5,1,6,7,9,8};
quick_sort(a,0,8);
for (int i=0; i<9;i++)
{
cout<<a[i]<<" ";
}
}
快速排序(递归和非递归)
最新推荐文章于 2023-06-11 23:26:34 发布