习题2-24

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

#include <iostream>
#include <vector>
#include <stack>
#include <ctime>
#include <cassert>
#include <cstring>

using namespace std;

const int N = 100;

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

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

 


 

 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值