1. 简介

TimSort 是一种稳定的, 自适应的变种归并排序. 当被应用在部分有序的数组排序问题时, TimSort 有远好于$O(NlogN)$的时间性能. 而在最差情况下, TimSort 也能保持与传统归并排序相近的表现.
从 JDK 1.7 开始被引入并成为 Java 中 Arrays 的默认排序算法.

2. 核心思想

TimSort 算法结合了归并排序和插入排序.

TimSort 算法为了减少对升序部分的回溯和对降序部分的性能倒退, 将输入按其升序和降序的特点进行了分区. 排序的输入单位不是一个个单独的数字, 而是一个个的分区. 每一个分区叫一个 run, 针对这些 run 进行排序. 每次拿出来两个 run 按照规则进行合并, 合并成一个 run 压入栈中. 直到栈中只剩一个 run. 这个 run 就是排序好的结果.

算法过程:

  1. 如果输入数组长度小于 32, 直接使用二分插入排序.
  2. 找到每个 run, 压入栈.
  3. 按照规则合并.

3. 源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
class TimSort<T> {

/**
* 使用 TimSort 算法的阈值, 小于此值使用 二分插入排序.
*/
private static final int MIN_MERGE = 32;

/**
* 待排序的数组
*/
private final T[] a;

/**
* 比较器(排序规则)
*/
private final Comparator<? super T> c;

/**
* 进入 gallop 模式的阈值
*/
private static final int MIN_GALLOP = 7;

/**
* 控制何时进入 gallop 模式.
*/
private int minGallop = MIN_GALLOP;

/**
* tem 数组的最大初始大小.
* 用于合并相关操作.
*/
private static final int INITIAL_TMP_STORAGE_LENGTH = 256;

/**
* 合并时使用的数组.
*/
private T[] tmp;
private int tmpBase;
private int tmpLen;

/**
* 压入栈中的 run 的个数
*/
private int stackSize = 0;
private final int[] runBase; // 每个 run 的起始索引
private final int[] runLen; // 每个 run 的长度.

/**
* 创建 TimSort 实例以维护正在进行的排序状态.
*/
private TimSort(T[] a, Comparator<? super T> c, T[] work, int workBase, int workLen) {
this.a = a;
this.c = c;

// 分配临时存储 tem
// 如有必要,可以在以后增加
int len = a.length;
int tlen = (len < 2 * INITIAL_TMP_STORAGE_LENGTH) ?
len >>> 1 : INITIAL_TMP_STORAGE_LENGTH;
if (work == null || workLen < tlen || workBase + tlen > work.length) {
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
T[] newArray = (T[])java.lang.reflect.Array.newInstance
(a.getClass().getComponentType(), tlen);
tmp = newArray;
tmpBase = 0;
tmpLen = tlen;
}
else {
tmp = work;
tmpBase = workBase;
tmpLen = workLen;
}

/*
* 根据原数组长度,为序列栈分配初始空间
*/
int stackLen = (len < 120 ? 5 :
len < 1542 ? 10 :
len < 119151 ? 24 : 49);
runBase = new int[stackLen];
runLen = new int[stackLen];
}

/*
* 排序
*/
static <T> void sort(T[] a, int lo, int hi, Comparator<? super T> c,
T[] work, int workBase, int workLen) {
// 断言, 保证后面的条件成立, 多用于调试阶段
// 除非手动打开, 否则无用
assert c != null && a != null && lo >= 0 && lo <= hi && hi <= a.length;

int nRemaining = hi - lo;
if (nRemaining < 2)
return; // 长度为 0 或 1 数组总是有序的.

// 数组长度小于 32, 直接使用二分插入排序.
if (nRemaining < MIN_MERGE) {
// 寻找第一个 run
// 执行完成之后. [lo, lo+initRunLen) 是有序的.
int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
// 二分插入排序
binarySort(a, lo, hi, lo + initRunLen, c);
return;
}

/**
* 新建一个 TimSort 实例, 存储运行时的状态, 比如临时的 run
*/
TimSort<T> ts = new TimSort<>(a, c, work, workBase, workLen);
// 当 run 块长度小于 minRun 时, 使用二分插入排序. (MIN_MERGE / 2 <= minRun <= MIN_MERGE)
int minRun = minRunLength(nRemaining);
do {
// 寻找下一个 run
int runLen = countRunAndMakeAscending(a, lo, hi, c);

// run 太短了, 扩展到 min(minRun, nRemaining) 使用二分插入排序.
if (runLen < minRun) {
// 排到最后剩余元素可能不足 minRun 个.
int force = nRemaining <= minRun ? nRemaining : minRun;
// 二分插入排序
binarySort(a, lo, lo + force, lo + runLen, c);
// 更新 run 长度.
runLen = force;
}

// 将 run 压入栈中
ts.pushRun(lo, runLen);
// 根据栈中的 run 块长度选择合并.
ts.mergeCollapse();

// 更新, 继续寻找
lo += runLen;
nRemaining -= runLen;
} while (nRemaining != 0);

assert lo == hi;
// 合并剩余的 run
ts.mergeForceCollapse();
assert ts.stackSize == 1;
}

/**
* 二分插入排序
*
* @param a 总数组, 只对 a 的 [lo, hi) 部分进行排序
* @param lo 要排序的范围第一个元素的索引.
* @param hi 要排序的范围最后一个元素之后的索引
* @param start [lo,start) 是有序的, 从 start 开始乱序.
*/
@SuppressWarnings("fallthrough")
private static <T> void binarySort(T[] a, int lo, int hi, int start,
Comparator<? super T> c) {
assert lo <= start && start <= hi;
if (start == lo)
start++;

for ( ; start < hi; start++) {
// 待插入的数据
T pivot = a[start];

// 在 [left, right] 中找到插入 privot 的位置.
int left = lo;
int right = start;
assert left <= right;
/*
* 寻找插入的位置
*/
while (left < right) {
int mid = (left + right) >>> 1;
if (c.compare(pivot, a[mid]) < 0)
right = mid;
else
left = mid + 1;
}
assert left == right;


int n = start - left; // 需要移动的元素的数量
// 如果待移动的元素 <= 2 个, 直接移动
// 减少 System.arraycopy 的调用
switch (n) {
case 2: a[left + 2] = a[left + 1];
case 1: a[left + 1] = a[left];
break;
default: System.arraycopy(a, left, a, left + 1, n);
}
// 插入元素
a[left] = pivot;
}
}

/**
* 寻找 run 的函数.
*/
private static <T> int countRunAndMakeAscending(T[] a, int lo, int hi,
Comparator<? super T> c) {
assert lo < hi;
int runHi = lo + 1;
if (runHi == hi)
return 1;

// 寻找 run
if (c.compare(a[runHi++], a[lo]) < 0) { // 降序
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
runHi++;
// 原地反转数组, 使其变为升序
reverseRange(a, lo, runHi);
} else { // 升序
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
runHi++;
}
return runHi - lo;
}

/**
* 原地反转数组
*/
private static void reverseRange(Object[] a, int lo, int hi) {
hi--;
while (lo < hi) {
Object t = a[lo];
a[lo++] = a[hi];
a[hi--] = t;
}
}

/**
* 求 minRun
* minRun: 小于 minRun 的 run, 扩展为 min(minRun, 剩余元素), 使用二分插入排序.
*/
private static int minRunLength(int n) {
assert n >= 0;
int r = 0;


// n < MIN_MERGE 直接使用二分插入排序了, 不会调用此方法
// 若 n 为 2 的幂, 那么 r 最终会为 0, 返回结果是 MIN_MERGE / 2
// 在剩余情况下, 返回值 k 落在 [MIN_MERGE/2, MIN_MERGE] 间
// 同时保证 n / k 接近且严格小于一个 2 的幂
while (n >= MIN_MERGE) {
r |= (n & 1);
n >>= 1;
}
return n + r;
}

/**
* 将 run 压入栈.
*
* @param runBase run 第一个元素的索引
* @param runLen run 的长度
*/
private void pushRun(int runBase, int runLen) {
this.runBase[stackSize] = runBase;
this.runLen[stackSize] = runLen;
stackSize++;
}

/**
* 根据栈顶的三个 run 的长度进行选择合并
* 将较短的二个合并(i-1 和 i-2 或者 i-2 和 i-3)
* (和 2048 游戏差不多)
*/
private void mergeCollapse() {
while (stackSize > 1) {
int n = stackSize - 2;
if (n > 0 && runLen[n-1] <= runLen[n] + runLen[n+1]) {
if (runLen[n - 1] < runLen[n + 1])
n--;
mergeAt(n);
} else if (runLen[n] <= runLen[n + 1]) {
mergeAt(n);
} else {
break;
}
}
}

/**
* 合并栈中的所有 run, 直到只剩下一个 run
*/
private void mergeForceCollapse() {
while (stackSize > 1) {
int n = stackSize - 2;
// 判断 合并 i-1 i-2 还是合并 i-3 i-2
// 和上个方法一个道理
// 尽量合并短的
if (n > 0 && runLen[n - 1] < runLen[n + 1])
n--;
mergeAt(n);
}
}

/**
* 合并栈中的第 i 个和第 i + 1 个 run
* i 必须时倒数第二个或者倒数第三个
*/
private void mergeAt(int i) {
assert stackSize >= 2;
assert i >= 0;
assert i == stackSize - 2 || i == stackSize - 3;

int base1 = runBase[i];
int len1 = runLen[i];
int base2 = runBase[i + 1];
int len2 = runLen[i + 1];
assert len1 > 0 && len2 > 0;
assert base1 + len1 == base2;

/*
* 更新 run 的长度
*/
runLen[i] = len1 + len2;
// 如果准备进行归并的是倒数第二和倒数第三的序列, 那么还需要维护倒数第一序列的状态
if (i == stackSize - 3) {
runBase[i + 1] = runBase[i + 2];
runLen[i + 1] = runLen[i + 2];
}
stackSize--;

/*
* 目前我们有 run1: [base1, base1 + len1) 和 run2 : [base2, base2 + len2)
* 其中 base1 + len1 == base2
* 首先尝试在 run1 中寻找一个索引 base1 + k
* 使得 [base1 + k, base1 + len1) 中的每一个元素都比 run2 中的元素小
* 从而减少实际需进行归并操作的 run 的长度
*/
int k = gallopRight(a[base2], a, base1, len1, 0, c);
assert k >= 0;
base1 += k;
len1 -= k;
// 说明 run1 和 run2 已经是有序的了
if (len1 == 0)
return;

/*
* 与上一段类似, 在 run2 中寻找索引 base2 + k
* 使得 [base2 + k, base2 + len2) 中每一个元素都比 run1 中的元素大
*/
len2 = gallopLeft(a[base1 + len1 - 1], a, base2, len2, len2 - 1, c);
assert len2 >= 0;
// 说明 run1 和 run2 已经是有序的了
if (len2 == 0)
return;

// 合并剩余的元素, 长度短的 run 为基底.
if (len1 <= len2)
mergeLo(base1, len1, base2, len2);
else
mergeHi(base1, len1, base2, len2);
}

/**
* 查找最接近 key 的索引
* 使用的二分查找, 加了一些优化
*
* @param key 查找的值
* @param a 要在其中搜索的数组
* @param base 查找范围中的第一个元素的索引
* @param len 查找范围的长度
* @param hint 开始搜索的索引
* @param c 比较器(排序规则)
* @return k 使得 [base, base + k - 1] < key <= [base + k, base + len]
*/
private static <T> int gallopLeft(T key, T[] a, int base, int len, int hint,
Comparator<? super T> c) {
assert len > 0 && hint >= 0 && hint < len;
// 在经典二分查找开始前, 先尝试缩小查找范围
int lastOfs = 0;
int ofs = 1;
if (c.compare(key, a[base + hint]) > 0) {
// 查看 key 属于哪个区间
// [base + hint, base + hint + 1), [base + hint + 1, base + hint + 3), [base + hint + 3, base + hint + 7),[base + hint + 7, base + hint + 15)...
// 使 a[base+hint+lastOfs] < key <= a[base+hint+ofs]
int maxOfs = len - hint;
while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) > 0) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // 溢出
ofs = maxOfs;
}
if (ofs > maxOfs)
ofs = maxOfs;

// 更新下标, 相对 hint 进行偏移
// 之前的ofs和lastOfs都是相对于hint位置的, 现在把它重置为相对于base的位置
lastOfs += hint;
ofs += hint;
} else { // key <= a[base + hint]
// 和上面同样的思路
// 使 a[base+hint-ofs] < key <= a[base+hint-lastOfs]
final int maxOfs = hint + 1;
while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) <= 0) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // 溢出
ofs = maxOfs;
}
if (ofs > maxOfs)
ofs = maxOfs;

// 更新下标, 相对 hint 进行偏移
int tmp = lastOfs;
lastOfs = hint - ofs;
ofs = hint - tmp;
}
assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;

/*
* 在区间 [base + lastOfs, base + ofs) 上进行二分查找
*/
lastOfs++;
while (lastOfs < ofs) {
int m = lastOfs + ((ofs - lastOfs) >>> 1);

if (c.compare(key, a[base + m]) > 0)
lastOfs = m + 1; // a[base + m] < key
else
ofs = m; // key <= a[base + m]
}
assert lastOfs == ofs; // so a[base + ofs - 1] < key <= a[base + ofs]
return ofs;
}

/**
* 与上个方法对称
*/
private static <T> int gallopRight(T key, T[] a, int base, int len,
int hint, Comparator<? super T> c) {
assert len > 0 && hint >= 0 && hint < len;

int ofs = 1;
int lastOfs = 0;
if (c.compare(key, a[base + hint]) < 0) {
// Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs]
int maxOfs = hint + 1;
while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) < 0) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
if (ofs > maxOfs)
ofs = maxOfs;

// Make offsets relative to b
int tmp = lastOfs;
lastOfs = hint - ofs;
ofs = hint - tmp;
} else { // a[b + hint] <= key
// Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs]
int maxOfs = len - hint;
while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) >= 0) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
if (ofs > maxOfs)
ofs = maxOfs;

// Make offsets relative to b
lastOfs += hint;
ofs += hint;
}
assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;

/*
* Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to
* the right of lastOfs but no farther right than ofs. Do a binary
* search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs].
*/
lastOfs++;
while (lastOfs < ofs) {
int m = lastOfs + ((ofs - lastOfs) >>> 1);

if (c.compare(key, a[base + m]) < 0)
ofs = m; // key < a[b + m]
else
lastOfs = m + 1; // a[b + m] <= key
}
assert lastOfs == ofs; // so a[b + ofs - 1] <= key < a[b + ofs]
return ofs;
}

/**
* 以稳定的方式合并两个相邻的 run.
* a[base1] > a[base2]&& 第一个 run 的最后一个元素比第二个 run 的所有元素都大.
* 为了性能, 只有 len1 ≤ len2 时才调用此方法, 否则调用它的孪生兄弟 mergeHi.
* 如果 len1 == len2 可以调用任意一个方法.
*/
private void mergeLo(int base1, int len1, int base2, int len2) {
assert len1 > 0 && len2 > 0 && base1 + len1 == base2;

// 将第一个 run 复制到 tem
T[] a = this.a; // 出于性能考虑, 将类中的对象用本地变量形式声明出来
T[] tmp = ensureCapacity(len1);
// 声明游标 cursor1 和 cursor2 分别指向两个序列头部
int cursor1 = tmpBase; // 第一个 run 的起始索引
int cursor2 = base2; // 第二个 run 的起始索引
int dest = base1;
System.arraycopy(a, base1, tmp, cursor1, len1);

// 对一些极端情况的处理
a[dest++] = a[cursor2++];
if (--len2 == 0) {
// 如果 run2 只有一个元素
System.arraycopy(tmp, cursor1, a, dest, len1);
return;
}
if (len1 == 1) {
// 如果 run1 只有一个元素
System.arraycopy(a, cursor2, a, dest, len2);
// 将 run2 放入合适位置后在其后面加上 run1 的元素
a[dest + len2] = tmp[cursor1];
return;
}

Comparator<? super T> c = this.c; // 使用局部变量, 提高性能
int minGallop = this.minGallop;
outer:
while (true) {
// 一次元素比较中, 某个 run 的元素小, 算这个 run 赢了一次
int count1 = 0; // 第一个 run 赢的次数
int count2 = 0; // 第二个 run 赢的次数

/*
* D如果忽略 count1 和 count2 下面的循环就是经典的合并操作.
*/
do {
assert len1 > 1 && len2 > 0;
if (c.compare(a[cursor2], tmp[cursor1]) < 0) {
a[dest++] = a[cursor2++];
// 一个 run 赢了之后, 另一个 run 的 count 清零
// 所以 count 的实际意义为连赢的次数.
count2++;
count1 = 0;
if (--len2 == 0)
break outer;
} else {
a[dest++] = tmp[cursor1++];
count1++;
count2 = 0;
if (--len1 == 1)
break outer;
}
} while ((count1 | count2) < minGallop);

/*
* 某一个 run 连胜的次数太多了(> minGallop), 进入 gallop 模式.
* 接下来不再逐个比较, 而是通过 gallopRight 和 gallopLeft 比较.
* 目的是加快合并的过程.
*/
do {
assert len1 > 1 && len2 > 0;
// gallopRight 返回的是索引的偏移量
// 在此循环的逻辑下, 此返回值也恰好是 run1 连续赢的次数
count1 = gallopRight(a[cursor2], tmp, cursor1, len1, 0, c);
if (count1 != 0) {
System.arraycopy(tmp, cursor1, a, dest, count1);
dest += count1;
cursor1 += count1;
len1 -= count1;
if (len1 <= 1) // len1 == 1 || len1 == 0
break outer;
}
a[dest++] = a[cursor2++];
if (--len2 == 0)
break outer;
// 同理, run2
count2 = gallopLeft(tmp[cursor1], a, cursor2, len2, 0, c);
if (count2 != 0) {
System.arraycopy(a, cursor2, a, dest, count2);
dest += count2;
cursor2 += count2;
len2 -= count2;
if (len2 == 0)
break outer;
}
a[dest++] = tmp[cursor1++];
if (--len1 == 1)
break outer;
// 动态调整minGallop的值
minGallop--;
} while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
if (minGallop < 0)
minGallop = 0;
// 离开 gallop 模式惩罚
// 主要是为了优化, 避免连赢不多的情况进入 gallop
minGallop += 2;
} // End of "outer" loop
this.minGallop = minGallop < 1 ? 1 : minGallop; // 写回字段

if (len1 == 1) {
assert len2 > 0;
System.arraycopy(a, cursor2, a, dest, len2);
a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
} else if (len1 == 0) {
throw new IllegalArgumentException(
"Comparison method violates its general contract!");
} else {
assert len2 == 0;
assert len1 > 1;
System.arraycopy(tmp, cursor1, a, dest, len1);
}
}

/**
* 与 mergeLo 对称
*/
private void mergeHi(int base1, int len1, int base2, int len2) {
assert len1 > 0 && len2 > 0 && base1 + len1 == base2;

// Copy second run into temp array
T[] a = this.a; // For performance
T[] tmp = ensureCapacity(len2);
int tmpBase = this.tmpBase;
System.arraycopy(a, base2, tmp, tmpBase, len2);

int cursor1 = base1 + len1 - 1; // Indexes into a
int cursor2 = tmpBase + len2 - 1; // Indexes into tmp array
int dest = base2 + len2 - 1; // Indexes into a

// Move last element of first run and deal with degenerate cases
a[dest--] = a[cursor1--];
if (--len1 == 0) {
System.arraycopy(tmp, tmpBase, a, dest - (len2 - 1), len2);
return;
}
if (len2 == 1) {
dest -= len1;
cursor1 -= len1;
System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
a[dest] = tmp[cursor2];
return;
}

Comparator<? super T> c = this.c; // Use local variable for performance
int minGallop = this.minGallop; // " " " " "
outer:
while (true) {
int count1 = 0; // Number of times in a row that first run won
int count2 = 0; // Number of times in a row that second run won

/*
* Do the straightforward thing until (if ever) one run
* appears to win consistently.
*/
do {
assert len1 > 0 && len2 > 1;
if (c.compare(tmp[cursor2], a[cursor1]) < 0) {
a[dest--] = a[cursor1--];
count1++;
count2 = 0;
if (--len1 == 0)
break outer;
} else {
a[dest--] = tmp[cursor2--];
count2++;
count1 = 0;
if (--len2 == 1)
break outer;
}
} while ((count1 | count2) < minGallop);

/*
* One run is winning so consistently that galloping may be a
* huge win. So try that, and continue galloping until (if ever)
* neither run appears to be winning consistently anymore.
*/
do {
assert len1 > 0 && len2 > 1;
count1 = len1 - gallopRight(tmp[cursor2], a, base1, len1, len1 - 1, c);
if (count1 != 0) {
dest -= count1;
cursor1 -= count1;
len1 -= count1;
System.arraycopy(a, cursor1 + 1, a, dest + 1, count1);
if (len1 == 0)
break outer;
}
a[dest--] = tmp[cursor2--];
if (--len2 == 1)
break outer;

count2 = len2 - gallopLeft(a[cursor1], tmp, tmpBase, len2, len2 - 1, c);
if (count2 != 0) {
dest -= count2;
cursor2 -= count2;
len2 -= count2;
System.arraycopy(tmp, cursor2 + 1, a, dest + 1, count2);
if (len2 <= 1) // len2 == 1 || len2 == 0
break outer;
}
a[dest--] = a[cursor1--];
if (--len1 == 0)
break outer;
minGallop--;
} while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
if (minGallop < 0)
minGallop = 0;
minGallop += 2; // Penalize for leaving gallop mode
} // End of "outer" loop
this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field

if (len2 == 1) {
assert len1 > 0;
dest -= len1;
cursor1 -= len1;
System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
a[dest] = tmp[cursor2]; // Move first elt of run2 to front of merge
} else if (len2 == 0) {
throw new IllegalArgumentException(
"Comparison method violates its general contract!");
} else {
assert len1 == 0;
assert len2 > 0;
System.arraycopy(tmp, tmpBase, a, dest - (len2 - 1), len2);
}
}

/**
* 为 tmp 分配空间
* 出于性能考虑, 以指数方式增加
*/
private T[] ensureCapacity(int minCapacity) {
if (tmpLen < minCapacity) {
// 计算最小的大于 minCapacity 的 2 的幂
int newSize = minCapacity;
newSize |= newSize >> 1;
newSize |= newSize >> 2;
newSize |= newSize >> 4;
newSize |= newSize >> 8;
newSize |= newSize >> 16;
newSize++;

if (newSize < 0) // 不太可能, int 溢出
newSize = minCapacity;
else
newSize = Math.min(newSize, a.length >>> 1);

@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
T[] newArray = (T[])java.lang.reflect.Array.newInstance
(a.getClass().getComponentType(), newSize);
tmp = newArray;
tmpLen = newSize;
tmpBase = 0;
}
return tmp;
}
}

评论




博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议

载入天数...载入时分秒... 本站使用 Volantis 作为主题 鲁ICP备-20012065号