STL 中的List排序算法(in SGI STL)

  1. template <class T, class Alloc>
  2. void list<T, Alloc>::sort() {
  3.   if (node->next == node || link_type(node->next)->next == node) return;
  4.   list<T, Alloc> carry;
  5.   list<T, Alloc> counter[64];
  6.   int fill = 0;
  7.   while (!empty()) {
  8.     carry.splice(carry.begin(), *this, begin());
  9.     int i = 0;
  10.     while(i < fill && !counter[i].empty()) {
  11.       counter[i].merge(carry);
  12.       carry.swap(counter[i++]);
  13.     }
  14.     carry.swap(counter[i]);         
  15.     if (i == fill) ++fill;
  16.   } 
  17.   for (int i = 1; i < fill; ++i) counter[i].merge(counter[i-1]);
  18.   swap(counter[fill-1]);
  19. }

抛开算法复杂度不说,这个算法很好地复用了List类中定义的其它成员函数。

carry每次循环开始从this中splice头部的node,保证了参与merge的List始终是有序的。counter[]作为排序中介List,通过与carry中的数据merge达到排序的目的,swap的恰当使用保证了将carry中数据转至counter[],也保证了carry在循环开始可以轻装上阵,为splice做好准备。

算法思想别具一格,可谓STL算法中的上佳之作。

 

自己改了一下代码,以便可以显示排序过程:

  1. template <typename T>
  2. void sort_list(list<T> &lst)
  3. {
  4.  if(lst.size()<2)
  5.   return;
  6.  list<T> carry;
  7.  list<T> counter[64];
  8.  int fill = 0; 
  9.  typename list<T>::iterator it;
  10.  while (!lst.empty()) {
  11.      carry.splice(carry.begin(), lst, lst.begin());  
  12.   cout<<"carry: ";
  13.   it=carry.begin();
  14.   while(it!=carry.end())
  15.    cout<<*it++<<" ";
  16.   cout<<endl;
  17.      int i = 0;
  18.      while(i < fill && !counter[i].empty()) {
  19.          counter[i].merge(carry);
  20.          carry.swap(counter[i++]);
  21.      }
  22.      carry.swap(counter[i]);   
  23.   for(int i=0;i<fill+1;i++)
  24.   {
  25.    it=counter[i].begin();
  26.       cout<<"counter"<<i<<": ";
  27.       while(it!=counter[i].end())
  28.        cout<<*it++<<" ";
  29.       cout<<endl;
  30.   }
  31.      if (i == fill) ++fill;
  32.   cout<<endl;
  33.    } 
  34.     for (int i = 1; i < fill; ++i) counter[i].merge(counter[i-1]);
  35.  it=counter[fill-1].begin();
  36.  cout<<"counter"<<fill-1<<": ";
  37.  while(it!=counter[fill-1].end())
  38.   cout<<*it++<<" ";
  39.  cout<<endl;
  40.     lst.swap(counter[fill-1]);
  41. }
  42. int main()
  43. {
  44.  int arr[]={10,88,45,87,65,96,84,8,86,53,67,5,48,74,4,35,71,25,32};
  45.  list<int> lst(arr,arr+sizeof(arr)/sizeof(int));
  46.  list<int>::iterator it=lst.begin();
  47.  while(it!=lst.end())
  48.   cout<<*it++<<" ";
  49.  cout<<endl;
  50.  sort_list(lst);
  51.  return 0;
  52. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值