# include<iostream>
using namespace std;
# define maxsize 100
int partition(int a[], int low, int high){
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 quicksort(int a[], int n){
int stack[maxsize];
int top = -1;
// 首先入栈初始的 low 和 high
stack[++top] = 0;
stack[++top] = n - 1;
// 栈不空则一直循环
while(top > -1){
int high = stack[top--];
int low = stack[top--];
int pivotpos = partition(a, low, high);
if(pivotpos > low){
stack[++top] = low;
stack[++top] = pivotpos - 1;
}
if(pivotpos < high){
stack[++top] = pivotpos + 1;
stack[++top] = high;
}
}
}
int main(){
int a[] = {10, 9, 8, 4, 5, 7, 3, 2, 11, 18, 20};
int n = 11;
for(int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
quicksort(a, n);
for(int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
输出结果为:
10 9 8 4 5 7 3 2 11 18 20
2 3 4 5 7 8 9 10 11 18 20