#include <iostream>
#include <stack>
void swap(int* a, int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
};
int partition(int* a, int l, int r)
{
int pivot = a[r];
int front = l;
for(int i = l; i < r; i++)
{
if(a[i] < pivot)
{
swap(&a[i], &a[front]);
front++;
}
}
swap(&a[front], &a[r]);
return front;
};
void qSort(int* a, int l, int r)
{
std::stack<int> st;
do
{
while(l < r)
{
int pi = partition(a, l, r);
if((pi - l) < (r - pi))
{
st.push(pi + 1);
st.push(r);
r = pi - 1;
}
else
{
st.push(l);
st.push(pi - 1);
l = pi + 1;
l = r;
}
}
if(st.empty())
return;
r = st.top();
st.pop();
l = st.top();
st.pop();
}while(1);
};
int main()
{
int a[] = {21,5,45,88,4,3,1,0,65,123,111};
qSort(a, 0, 10);
int i = 0;
while(i < 11)
{
std::cout << a[i] << " ";
i++;
}
return 0;
}
快速排序非递归方法
最新推荐文章于 2023-03-18 10:06:50 发布