突然觉得C++挺有趣的,因此俺从今天开始改用C++了……
#include
#include
#include
#include
#include
#include
using namespace std;
const int N = 100;
int partition(vector
void qsort(vector
int swap(int&, int&);
int main()
{
int n, i, temp;
vector
while (cin >> n)
{
a.erase(a.begin(), a.end());
assert(a.empty());
for (i = 0; i < n; i++)
{
cin >> temp;
a.push_back(temp);
}
qsort(a, 0, n-1);
for (i = 0; i < n; i++)
cout << a[i] <<' ';
cout << endl;
}
return 0;
}
void qsort(vector
{
stack
int i, j;
int k = partition(a, left, right);
if (k + 1 < right)
{ S.push(right); S.push(k + 1); }
if (k - 1 > left)
{ S.push(k - 1); S.push(left); }
while (!S.empty())
{
while (!S.empty())
{
i = S.top(), S.pop();
j = S.top(), S.pop();
k = partition(a, i, j);
if (k - 1 > i)
{ T.push(i); T.push(k - 1); }
if (k + 1 < j)
{ T.push(k + 1); T.push(j); }
}
while (!T.empty())
{
S.push(T.top());
T.pop();
}
}
}
int partition(vector
{
int last, i;
srand(time(NULL));
if (left != right)
swap(a[left], a[rand()%(right - left) + left]);
for (last = left, i = left + 1; i <= right; i++)
{
if (a[i] < a[left])
swap(a[++last], a[i]);
}
swap(a[left], a[last]);
return last;
}
int swap(int &p, int &q)
{
int temp = p;
p = q;
q = temp;
return 0;
}