用快排对链表的排序--STL中list的sort函数

  由于标准库算法sort使用的是随机存取的迭代器,而list使用的的是双向迭代器,因此list要实现自己的sort函数。下面是源代码:

void sort()
{
  if(__node->__next == __node || __node->__next->__next == __node)
    return;

  list<T, Alloc> carry;
  list<T, Alloc> count[64];
  int fill = 0;
  while(!empty())
  {
    carry.splice(begin(), *this, begin());
    int i = 0;

    while (i < fill && !count[i].empty())
    {
      count[i].merge(carry);
      carry.swap(count[i++]);
    }
    carry.swap(count[i]);
    if (i == fill)
      ++fill;
  }

  for (int i = 0; i < fill; ++i)
  count[i].merge(count[i-1]);

  swap(count[i-1]);
}

假设list(待会用this表示这个list)中存放int型的值,并且为10, 30, 20, 60, 50, 25.先用这些数据来运行一下。

开始时

this: 10, 30, 20, 60, 50, 25

carry:null

count:null

进入第一次循环

this: 30, 20, 60, 50, 25

carry: 10

内循环不执行,结果

this: 30, 20, 60, 50, 25

carry:null

count[0]: 10

fill: 1

依次类推,第二次执行结果为

this: 20, 60, 50, 25

carry: null

count[0]:null

count[1]:10, 30

fill:2

第三次执行结果

this: 60, 50, 25

carry:null

count[0]:20

count[1]:10, 30

fill:2

第四次执行结果

this:50, 25

carry:null

count[0]:null

count[1]:null

count[2]:10, 20, 30, 60

fill:3

第五次执行结果

this:25

carry:null

count[0]:50

count[1]:null

count[2]:10, 20, 30, 60

fill:3

第六次执行结果

this:null

carry:null

count[0]:null;

count[1]:25, 50

count[2]:10, 20, 30, 60

接下来是将count数组归并,然后和this交换,完成排序。

  回顾整个过程,可以看出:carry的作用只是将一个list元素取出来以及充当count数组归并时的中间变量。count数组存放的是部分排序结果,而且从前面开始,只要count数组

有数据就将其归并。有趣的是count[i]最多存放2^i个元素。fill的作用是已经使用的count数组个数。

转载于:https://www.cnblogs.com/denghuan/p/4328481.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值