#include <stdio.h> #include <stack> using namespace std; void exch(int& a, int &b) { int tmp = a; a = b; b = tmp; } int partition(int a[], int l, int r) { int i=l-1; int j=r; int val = a[r]; while(1) { while(val > a[++i]); while(val < a[--j]) if(j == l) break; if(i >= j) break; exch(a[i], a[j]); } exch(a[i], a[r]); return i; } inline void push2(stack<int> &s, int a, int b) { s.push(b); s.push(a); } void quicksort(int a[], int l, int r) { stack<int> s; push2(s, l, r); while(!s.empty()) { l = s.top(); s.pop(); r = s.top(); s.pop(); if(l >= r) continue; int i = partition(a, l, r); //because of the size of stack if(i-l > r-i) { push2(s, l, i-1); push2(s, i+1, r); } else { push2(s, i+1, r); push2(s, l, i-1); } } } int main() { int a[10] = {4,3,6,5,3,1,8,9,6,5}; quicksort(a, 0, 9); for(int i=0; i<10; i++) printf("%d ", a[i]); printf("\n"); return 0; }