https://blog.csdn.net/nrsc272420199/article/details/82587933
理论基础在上文链接
代码实现
#include<iostream>
using namespace std;
int a[100] = { 5,33,3,7,11,6,8,100 };
void quickSort(int a[],int start,int end) {
if (start >= end)
return;
int i = start, j = end;
int temp = a[start];
bool flag = 0; //0时end从后往前扫描,1时start从前往后扫描
while (start != end) {
if (flag == 0) { //0时end从后往前扫描
if (a[end] > temp) {
end--;
}
else
{
a[start] = a[end];
start++;
flag = 1;
}
}
else //1时start从前往后扫描
{
if (a[start] < temp) {
start++;
}
else {
a[end] = a[start];
end--;
flag = 0;
}
}
}
a[start] = temp;
quickSort(a, i, start - 1);
quickSort(a, start + 1, j);
}
/*
非递归(栈)实现快排
*/
struct node {
int start;
int end;
};
void quickSort_2(int a[], int start, int end) {
stack<node* > st;
node *no = new node;
no->start = start;
no->end = end;
st.push(no);
while (!st.empty()){
start = st.top()->start;
end = st.top()->end;
if (start >= end)
return;
int i = start, j = end;
int temp = a[start];
bool flag = 0; //0时end从后往前扫描,1时start从前往后扫描
while (start != end) {
if (flag == 0) { //0时end从后往前扫描
if (a[end] > temp) {
end--;
}
else
{
a[start] = a[end];
start++;
flag = 1;
}
}
else //1时start从前往后扫描
{
if (a[start] < temp) {
start++;
}
else {
a[end] = a[start];
end--;
flag = 0;
}
}
}
a[start] = temp;
st.pop();
no->start = i;
no->end = start - 1;
st.push(no);
no->start = start + 1;
no->end = j;
st.push(no);
}
}
int main() {
int len = 8;
quickSort(a, 0, 7);
for (int i = 0; i < len; i++) cout << a[i] << " ";
return 0;
}