#include <iostream>
#include <vector>
#include <stack>
#include <time.h>
using namespace std;
//快速排序的递归实现和非递归实现
void QuickSortNormal(vector<int>& arr, const int left, const int right)
{
if (left >= right)
{
return;
}
int i = left;
int j = right;
int povit = arr[left];
while (i < j)
{
while (povit <= arr[j] && i < j)
{
j--;
}
while(povit >= arr[i] && i < j)
{
i++;
}
if (i < j)
{
swap(arr[i], arr[j]);
}
}
swap(arr[left], arr[j]);
QuickSortNormal(arr, left, j-1);
QuickSortNormal(arr, j+1, right);
}
//快排的非递归版本实现
void QuickSortNonRes(vector<int> &arr)
{
stack<pair<int, int>> s;
int left = 0;
int right = arr.size()-1;
s.push(make_pair(left, right));
while (!s.empty())
{
pair<int, int> p = s.top();
s.pop();
left = p.first;
right = p.second;
int i = p.first;
int j = p.second;
int povit = arr[left];
while (i < j)
{
while (povit <= arr[j] && i < j)
{
j--;
}
while (povit >= arr[i] && i < j)
{
i++;
}
if (i < j)
{
swap(arr[i], arr[j]);
}
}
swap(arr[left], arr[j]);
if (left < j-1)
{
s.push(make_pair(left, j-1));
}
if (j+1 < right)
{
s.push(make_pair(j+1, right));
}
}
}
int main()
{
srand((unsigned int)time(NULL));
vector<int> arr(10);
for (int i = 0; i < 10; i++)
{
arr[i] = rand()%100 + 1;
}
QuickSortNonRes(arr);
for (int i = 0; i < 10; i++)
{
cout << arr[i] << " ";
}
cout << endl;
system("pause");
return 0;
}