#include <iostream>
#include <stack>
using namespace std;
int partition(int a[], int low, int high){
int pivok = a[low];
while(low<high){
while(low<high && a[high]>pivok) high--;
a[low] = a[high];
while(low<high && a[low]<pivok) low++;
a[high] = a[low];
}
a[low] = pivok;
return low;
}
void insertSort(int a[], int low, int high){
int i, j;
int t;
for(i=low+1; i<=high; i++){
if(a[i] < a[i-1]){
t = a[i];
for(j=i-1; j>=low; j--){
if(a[j] > t)
a[j+1] = a[j];
else
break;
}
a[j+1] = t;
}
}
}
void quickSort(int a[], int low, int high){
if(high-low+1 <= 1)
return;
if((high-low+1) <=3){
insertSort(a, low, high);
return;
}
stack<int> s;
int mid = partition(a, low, high);
if(mid > 1){
s.push(low);
s.push(mid-1);
}
if(mid < (high-low+1)-2){
s.push(mid+1);
s.push((high-low+1)-1);
}
while(!s.empty()){
int right = s.top();
s.pop();
int left = s.top();
s.pop();
if((right-left+1) <3){
insertSort(a, left, right);
}else{
mid = partition(a, left, right);
if(left < mid-1){
s.push(left);
s.push(mid-1);
}
if(right > mid+1){
s.push(mid+1);
s.push(right);
}
}
}
}
int main(){
int a[] = {1,5,2,3,4};
int len = sizeof(a)/sizeof(int);
quickSort(a, 0, len-1);
for(int i=0; i<len; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}