习题2-24

  突然觉得C++挺有趣的,因此俺从今天开始改用C++了……

#include
#include
#include
#include
#include
#include

using namespace std;

const int N = 100;

int partition(vector&, int, int);
void qsort(vector&, int, int);
int swap(int&, int&);

int main()
{
 int n, i, temp;
 vectora;
 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 &a, int left, int right)
{
 stack S, T;
 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 &a, int left, int right)
{
 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;
}

 


 

 
 

你可能感兴趣的:(算法,iostream,vector,null)