今天翻看候jj的STL 源码剖析,看到list的sort算法,跟我之前所认为的list的排序算法有比较大的出入,特拿来品味一番。
源码
1
template
<
class
T,
class
Alloc
=
alloc
>
2
3 void list < T, alloc > ::sort()
4 {
5 if (node -> next == node || (link_type)( * node -> next) -> next == node)
6 {
7 return ;
8 }
9
10 list < T, Alloc > carry;
11 list < T, Alloc > counter[ 64 ];
12 int fill = 0 ;
13 while ( ! empty())
14 {
15 carry.splice(carry.begin(), * this , begin());
16 int i = 0 ;
17 while (i < fill && ! counter[i].empty())
18 {
19 counter[i].merge(carry);
20 carry.swap(counter[i ++ ]);
21 }
22 carry.swap(counter[i]);
23 if (i == fill)
24 ++ fill;
25 }
26
27 for ( int i = 1 ; i < fill; i ++ )
28 {
29 counter[i].merge(counter[i - 1 ]);
30 }
31 swap(counter[fill - 1 ]);
32
33 }
2
3 void list < T, alloc > ::sort()
4 {
5 if (node -> next == node || (link_type)( * node -> next) -> next == node)
6 {
7 return ;
8 }
9
10 list < T, Alloc > carry;
11 list < T, Alloc > counter[ 64 ];
12 int fill = 0 ;
13 while ( ! empty())
14 {
15 carry.splice(carry.begin(), * this , begin());
16 int i = 0 ;
17 while (i < fill && ! counter[i].empty())
18 {
19 counter[i].merge(carry);
20 carry.swap(counter[i ++ ]);
21 }
22 carry.swap(counter[i]);
23 if (i == fill)
24 ++ fill;
25 }
26
27 for ( int i = 1 ; i < fill; i ++ )
28 {
29 counter[i].merge(counter[i - 1 ]);
30 }
31 swap(counter[fill - 1 ]);
32
33 }