#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;
template <class T>
int partition(T *array, int begin, int end )
{
T index_value = array[begin];
int i = begin;
int j = end + 1;
while(1)
{
for(++i;i < j; ++i)
{
if(array[i] > index_value)
break;
}
for(--j;j > i; --j)
{
if(array[j] < index_value)
break;
}
if(j > i)
swap(array[i], array[j]);
else
break;
}
swap(array[begin], array[j]);
return j;
}
template <class T>
int partition2(T *array, int begin, int end )
{
T index_value = array[begin];
int i = begin;
int j = end;
while(i < j)
{
while(i < j && array[j] >= index_value)
--j;
if(i < j)
array[i++] = array[j];
while(i < j && array[i] < index_value)
++i;
if(i < j)
array[j--] = array[i];
}
array[i] = index_value;
return i;
}
template <class T>
int partition1(T * array, int begin, int end)
{
T index_value = array[end];
int i = begin - 1;
int j = begin;
for(;j < end; ++j)
{
if(array[j] < index_value)
{
++i;
if(i != j)
{
swap(array[j], array[i]);
}
}
}
swap(array[end], array[i + 1]);
return i + 1;
}
template <class T>
void quick_sort(T *array, int begin, int end)
{
int pos = 0;
if(begin < end)
{
pos = partition2<int>(array, begin, end);
}
else
return ;
quick_sort<T>(array, begin, pos - 1);
quick_sort<T>(array, pos + 1, end);
}
template<class T>
void quick_sort_non_recursion(T *array, int begin, int end)
{
stack<int> _stack;
_stack.push(begin);
_stack.push(end);
for(;!_stack.empty();)
{
int _end = _stack.top();
_stack.pop();
int _begin = _stack.top();
_stack.pop();
int pos = 0;
if(_begin < _end)
pos = partition1<int>(array, _begin, _end);
else
continue ;
_stack.push(pos + 1);
_stack.push(_end);
_stack.push(_begin);
_stack.push(pos - 1);
}
}
int main()
{
int array[10] = { 2 , 4, 1, 18, 5, 3, 23, 11, 5, 9};
quick_sort<int>(array, 0, 9);
int i = 0;
for (;i < 10; ++i)
cout << array[i] << "\t";
cout << endl;
return 0;
}