快速排序的非递归实现

来源:互联网 发布:ghost预装软件 编辑:程序博客网 时间:2024/05/20 08:01
#include <iostream>    
#include<vector>
using namespace std;    


void print_array(int array[], int len)
{
for (int i = 0; i < len; i++)
{
cout << array[i] << " ";
}
cout << endl;
}


int Partition(int array[], int low, int high)
{
int tmp = array[low];
while (low < high)
{
while(low < high && array[high] >= tmp) high--;
array[low] = array[high];
while(low < high && array[low] <= tmp) low++;
array[high] = array[low];
}
array[low] = tmp;
return low;
}


//快速排序 非递归


void Not_Recursion_QSort(int array[], int low, int high)
{
vector<int> v;
if (low < high)
{
v.push_back(low);
v.push_back(high);
}
int mid;
int tmp;
int tmp_low;
int tmp_high;
while (v.size())
{
tmp_high = v.back();
v.pop_back();
tmp_low = v.back();
v.pop_back();
tmp = Partition(array, tmp_low, tmp_high);
if (tmp-1 > tmp_low)
{
v.push_back(tmp_low);
v.push_back(tmp-1);
}
if (tmp + 1 < tmp_high)
{
v.push_back(tmp + 1);
v.push_back(tmp_high);
}
}
}


void main() 
{
int array[] = {1, 14, 25, 12};
int len = 4;
Not_Recursion_QSort(array, 0, len);

print_array(array, len);
}