由于标准库算法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数组个数。