Debian Codegraph @

rpython/rlib/listsort.py

raw symbols SCIP
1 from rpython.rlib.rarithmetic import ovfcheck
2 from rpython.rlib.objectmodel import specialize
3
4
5 ## ------------------------------------------------------------------------
6 ## Lots of code for an adaptive, stable, natural mergesort. There are many
7 ## pieces to this algorithm; read listsort.txt for overviews and details.
8 ## ------------------------------------------------------------------------
9 ## Adapted from CPython, original code and algorithms by Tim Peters
10
11
12 def merge_compute_minrun(n):
13 # Compute a good value for the minimum run length; natural runs shorter
14 # than this are boosted artificially via binary insertion.
15 #
16 # If n < 64, return n (it's too small to bother with fancy stuff).
17 # Else if n is an exact power of 2, return 32.
18 # Else return an int k, 32 <= k <= 64, such that n/k is close to, but
19 # strictly less than, an exact power of 2.
20 #
21 # See listsort.txt for more info.
22 r = 0 # becomes 1 if any 1 bits are shifted off
23 while n >= 64:
24 r |= n & 1
25 n >>= 1
26 return n + r
27
28 def powerloop(s1, n1, n2, n):
29 # Two adjacent runs begin at index s1. The first run has length n1, and
30 # the second run (starting at index s1+n1) has length n2. The list has total
31 # length n.
32 # Compute the "power" of the first run. See listsort.txt for details.
33 assert s1 >= 0
34 assert n1 >= 1 and n2 >= 1
35 assert s1 + n1 + n2 <= n
36 # a' = s1 + n1/2
37 # b' = s1 + n1 + n2/2 = a' + (n1 + n2)/2
38 a = 2 * s1 + n1 # 2 * a'
39 b = a + n1 + n2 # 2 * b'
40 result = 0
41 while True:
42 result += 1
43 if a >= n:
44 assert b >= a
45 a -= n
46 b -= n
47 elif b >= n:
48 break
49 assert a < b < n
50 a <<= 1
51 b <<= 1
52 return result
53
54 def make_timsort_class(getitem=None, setitem=None, length=None,
55 getitem_slice=None, lt=None):
56
57 if getitem is None:
58 def getitem(list, item):
59 return list[item]
60
61 if setitem is None:
62 def setitem(list, item, value):
63 list[item] = value
64
65 if length is None:
66 def length(list):
67 return len(list)
68
69 if getitem_slice is None:
70 def getitem_slice(list, start, stop):
71 return list[start:stop]
72
73 if lt is None:
74 def lt(a, b):
75 return a < b
76
77 class TimSort(object):
78 """TimSort(list).sort()
79
80 Sorts the list in-place, using the overridable method lt() for comparison.
81 """
82
83 def __init__(self, list, listlength=None):
84 self.list = list
85 if listlength is None:
86 listlength = length(list)
87 self.listlength = listlength
88 self.scratch_list = None
89
90 def setitem(self, item, val):
91 setitem(self.list, item, val)
92
93 def lt(self, a, b):
94 return lt(a, b)
95
96 def le(self, a, b):
97 return not self.lt(b, a) # always use self.lt() as the primitive
98
99 # binarysort is the best method for sorting small arrays: it does
100 # few compares, but can do data movement quadratic in the number of
101 # elements.
102 # "a" is a contiguous slice of a list, and is sorted via binary insertion.
103 # This sort is stable.
104 # On entry, the first "sorted" elements are already sorted.
105 # Even in case of error, the output slice will be some permutation of
106 # the input (nothing is lost or duplicated).
107
108 def binarysort(self, a, sorted=1):
109 abase = a.base
110 alist = a.list
111 for start in xrange(a.base + sorted, a.base + a.len):
112 # set l to where list[start] belongs
113 l = abase
114 r = start
115 pivot = getitem(alist, r)
116 # Invariants:
117 # pivot >= all in [base, l).
118 # pivot < all in [r, start).
119 # The second is vacuously true at the start.
120 while l < r:
121 p = l + ((r - l) >> 1)
122 if self.lt(pivot, getitem(alist, p)):
123 r = p
124 else:
125 l = p+1
126 assert l == r
127 # The invariants still hold, so pivot >= all in [base, l) and
128 # pivot < all in [l, start), so pivot belongs at l. Note
129 # that if there are elements equal to pivot, l points to the
130 # first slot after them -- that's why this sort is stable.
131 # Slide over to make room.
132 for p in xrange(start, l, -1):
133 setitem(alist, p, getitem(alist, p-1))
134 setitem(alist, l, pivot)
135
136 # Compute the length of the run in the slice "a".
137 # "A run" is the longest ascending sequence, with
138 #
139 # a[0] <= a[1] <= a[2] <= ...
140 #
141 # or the longest descending sequence, with
142 #
143 # a[0] > a[1] > a[2] > ...
144 #
145 # Return (run, descending) where descending is False in the former case,
146 # or True in the latter.
147 # For its intended use in a stable mergesort, the strictness of the defn of
148 # "descending" is needed so that the caller can safely reverse a descending
149 # sequence without violating stability (strict > ensures there are no equal
150 # elements to get out of order).
151
152 def count_run(self, a, resultrun):
153 if a.len <= 1:
154 n = a.len
155 descending = False
156 else:
157 n = 2
158 if self.lt(a.getitem(a.base + 1), a.getitem(a.base)):
159 descending = True
160 for p in xrange(a.base + 2, a.base + a.len):
161 if self.lt(a.getitem(p), a.getitem(p-1)):
162 n += 1
163 else:
164 break
165 else:
166 descending = False
167 for p in xrange(a.base + 2, a.base + a.len):
168 if self.lt(a.getitem(p), a.getitem(p-1)):
169 break
170 else:
171 n += 1
172 resultrun.len = n
173 return descending
174
175 # Locate the proper position of key in a sorted vector; if the vector
176 # contains an element equal to key, return the position immediately to the
177 # left of the leftmost equal element -- or to the right of the rightmost
178 # equal element if the flag "rightmost" is set.
179 #
180 # "hint" is an index at which to begin the search, 0 <= hint < a.len.
181 # The closer hint is to the final result, the faster this runs.
182 #
183 # The return value is the index 0 <= k <= a.len such that
184 #
185 # a[k-1] < key <= a[k] (if rightmost is False)
186 # a[k-1] <= key < a[k] (if rightmost is True)
187 #
188 # as long as the indices are in bound. IOW, key belongs at index k;
189 # or, IOW, the first k elements of a should precede key, and the last
190 # n-k should follow key.
191
192 # hint for the annotator: the argument 'rightmost' is always passed in as
193 # a constant (either True or False), so we can specialize the function for
194 # the two cases. (This is actually needed for technical reasons: the
195 # variable 'lower' must contain a known method, which is the case in each
196 # specialized version but not in the unspecialized one.)
197 @specialize.arg(4)
198 def gallop(self, key, a, hint, rightmost):
199 assert 0 <= hint < a.len
200 if rightmost:
201 lower = self.le # search for the largest k for which a[k] <= key
202 else:
203 lower = self.lt # search for the largest k for which a[k] < key
204
205 p = a.base + hint
206 lastofs = 0
207 ofs = 1
208 if lower(a.getitem(p), key):
209 # a[hint] < key -- gallop right, until
210 # a[hint + lastofs] < key <= a[hint + ofs]
211
212 maxofs = a.len - hint # a[a.len-1] is highest
213 while ofs < maxofs:
214 if lower(a.getitem(p + ofs), key):
215 lastofs = ofs
216 try:
217 ofs = ovfcheck(ofs << 1)
218 except OverflowError:
219 ofs = maxofs
220 else:
221 ofs = ofs + 1
222 else: # key <= a[hint + ofs]
223 break
224
225 if ofs > maxofs:
226 ofs = maxofs
227 # Translate back to offsets relative to a.
228 lastofs += hint
229 ofs += hint
230
231 else:
232 # key <= a[hint] -- gallop left, until
233 # a[hint - ofs] < key <= a[hint - lastofs]
234 maxofs = hint + 1 # a[0] is lowest
235 while ofs < maxofs:
236 if lower(a.getitem(p - ofs), key):
237 break
238 else:
239 # key <= a[hint - ofs]
240 lastofs = ofs
241 try:
242 ofs = ovfcheck(ofs << 1)
243 except OverflowError:
244 ofs = maxofs
245 else:
246 ofs = ofs + 1
247 if ofs > maxofs:
248 ofs = maxofs
249 # Translate back to positive offsets relative to a.
250 lastofs, ofs = hint-ofs, hint-lastofs
251
252 assert -1 <= lastofs < ofs <= a.len
253
254 # Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
255 # right of lastofs but no farther right than ofs. Do a binary
256 # search, with invariant a[lastofs-1] < key <= a[ofs].
257
258 lastofs += 1
259 while lastofs < ofs:
260 m = lastofs + ((ofs - lastofs) >> 1)
261 if lower(a.getitem(a.base + m), key):
262 lastofs = m+1 # a[m] < key
263 else:
264 ofs = m # key <= a[m]
265
266 assert lastofs == ofs # so a[ofs-1] < key <= a[ofs]
267 return ofs
268
269
270 # ____________________________________________________________
271
272 # When we get into galloping mode, we stay there until both runs win less
273 # often than MIN_GALLOP consecutive times. See listsort.txt for more info.
274 MIN_GALLOP = 7
275
276 def merge_init(self):
277 # This controls when we get *into* galloping mode. It's initialized
278 # to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
279 # random data, and lower for highly structured data.
280 self.min_gallop = self.MIN_GALLOP
281
282 # A stack of n pending runs yet to be merged. Run #i starts at
283 # address pending[i].base and extends for pending[i].len elements.
284 # It's always true (so long as the indices are in bounds) that
285 #
286 # pending[i].base + pending[i].len == pending[i+1].base
287 #
288 # so we could cut the storage for this, but it's a minor amount,
289 # and keeping all the info explicit simplifies the code.
290 self.pending = []
291
292 # Merge the slice "a" with the slice "b" in a stable way, in-place.
293 # a.len and b.len must be > 0, and a.base + a.len == b.base.
294 # Must also have that b.list[b.base] < a.list[a.base], that
295 # a.list[a.base+a.len-1] belongs at the end of the merge, and should have
296 # a.len <= b.len. See listsort.txt for more info.
297
298 def merge_lo(self, a, b):
299 assert a.len > 0 and b.len > 0 and a.base + a.len == b.base
300 min_gallop = self.min_gallop
301 dest = a.base
302 a.copyitems(self)
303
304 # Invariant: elements in "a" are waiting to be reinserted into the list
305 # at "dest". They should be merged with the elements of "b".
306 # b.base == dest + a.len.
307 # We use a finally block to ensure that the elements remaining in
308 # the copy "a" are reinserted back into self.list in all cases.
309 try:
310 self.setitem(dest, b.popleft())
311 dest += 1
312 if a.len == 1 or b.len == 0:
313 return
314
315 while True:
316 acount = 0 # number of times A won in a row
317 bcount = 0 # number of times B won in a row
318
319 # Do the straightforward thing until (if ever) one run
320 # appears to win consistently.
321 while True:
322 if self.lt(b.getitem(b.base), a.getitem(a.base)):
323 self.setitem(dest, b.popleft())
324 dest += 1
325 if b.len == 0:
326 return
327 bcount += 1
328 acount = 0
329 if bcount >= min_gallop:
330 break
331 else:
332 self.setitem(dest, a.popleft())
333 dest += 1
334 if a.len == 1:
335 return
336 acount += 1
337 bcount = 0
338 if acount >= min_gallop:
339 break
340
341 # One run is winning so consistently that galloping may
342 # be a huge win. So try that, and continue galloping until
343 # (if ever) neither run appears to be winning consistently
344 # anymore.
345 min_gallop += 1
346
347 while True:
348 min_gallop -= min_gallop > 1
349 self.min_gallop = min_gallop
350
351 acount = self.gallop(b.getitem(b.base), a, hint=0,
352 rightmost=True)
353 for p in xrange(a.base, a.base + acount):
354 self.setitem(dest, a.getitem(p))
355 dest += 1
356 a.advance(acount)
357 # a.len==0 is impossible now if the comparison
358 # function is consistent, but we can't assume
359 # that it is.
360 if a.len <= 1:
361 return
362
363 self.setitem(dest, b.popleft())
364 dest += 1
365 if b.len == 0:
366 return
367
368 bcount = self.gallop(a.getitem(a.base), b, hint=0,
369 rightmost=False)
370 for p in xrange(b.base, b.base + bcount):
371 self.setitem(dest, b.getitem(p))
372 dest += 1
373 b.advance(bcount)
374 if b.len == 0:
375 return
376
377 self.setitem(dest, a.popleft())
378 dest += 1
379 if a.len == 1:
380 return
381
382 if acount < self.MIN_GALLOP and bcount < self.MIN_GALLOP:
383 break
384
385 min_gallop += 1 # penalize it for leaving galloping mode
386 self.min_gallop = min_gallop
387
388 finally:
389 # The last element of a belongs at the end of the merge, so we copy
390 # the remaining elements of b before the remaining elements of a.
391 assert a.len >= 0 and b.len >= 0
392 for p in xrange(b.base, b.base + b.len):
393 self.setitem(dest, b.getitem(p))
394 dest += 1
395 for p in xrange(a.base, a.base + a.len):
396 self.setitem(dest, a.getitem(p))
397 dest += 1
398
399 # Same as merge_lo(), but should have a.len >= b.len.
400
401 def merge_hi(self, a, b):
402 assert a.len > 0 and b.len > 0 and a.base + a.len == b.base
403 min_gallop = self.min_gallop
404 dest = b.base + b.len
405 b.copyitems(self)
406
407 # Invariant: elements in "b" are waiting to be reinserted into the list
408 # before "dest". They should be merged with the elements of "a".
409 # a.base + a.len == dest - b.len.
410 # We use a finally block to ensure that the elements remaining in
411 # the copy "b" are reinserted back into self.list in all cases.
412 try:
413 dest -= 1
414 self.setitem(dest, a.popright())
415 if a.len == 0 or b.len == 1:
416 return
417
418 while True:
419 acount = 0 # number of times A won in a row
420 bcount = 0 # number of times B won in a row
421
422 # Do the straightforward thing until (if ever) one run
423 # appears to win consistently.
424 while True:
425 nexta = a.getitem(a.base + a.len - 1)
426 nextb = b.getitem(b.base + b.len - 1)
427 if self.lt(nextb, nexta):
428 dest -= 1
429 self.setitem(dest, nexta)
430 a.len -= 1
431 if a.len == 0:
432 return
433 acount += 1
434 bcount = 0
435 if acount >= min_gallop:
436 break
437 else:
438 dest -= 1
439 self.setitem(dest, nextb)
440 b.len -= 1
441 if b.len == 1:
442 return
443 bcount += 1
444 acount = 0
445 if bcount >= min_gallop:
446 break
447
448 # One run is winning so consistently that galloping may
449 # be a huge win. So try that, and continue galloping until
450 # (if ever) neither run appears to be winning consistently
451 # anymore.
452 min_gallop += 1
453
454 while True:
455 min_gallop -= min_gallop > 1
456 self.min_gallop = min_gallop
457
458 nextb = b.getitem(b.base + b.len - 1)
459 k = self.gallop(nextb, a, hint=a.len-1, rightmost=True)
460 acount = a.len - k
461 for p in xrange(a.base + a.len - 1, a.base + k - 1, -1):
462 dest -= 1
463 self.setitem(dest, a.getitem(p))
464 a.len -= acount
465 if a.len == 0:
466 return
467
468 dest -= 1
469 self.setitem(dest, b.popright())
470 if b.len == 1:
471 return
472
473 nexta = a.getitem(a.base + a.len - 1)
474 k = self.gallop(nexta, b, hint=b.len-1, rightmost=False)
475 bcount = b.len - k
476 for p in xrange(b.base + b.len - 1, b.base + k - 1, -1):
477 dest -= 1
478 self.setitem(dest, b.getitem(p))
479 b.len -= bcount
480 # b.len==0 is impossible now if the comparison
481 # function is consistent, but we can't assume
482 # that it is.
483 if b.len <= 1:
484 return
485
486 dest -= 1
487 self.setitem(dest, a.popright())
488 if a.len == 0:
489 return
490
491 if acount < self.MIN_GALLOP and bcount < self.MIN_GALLOP:
492 break
493
494 min_gallop += 1 # penalize it for leaving galloping mode
495 self.min_gallop = min_gallop
496
497 finally:
498 # The last element of a belongs at the end of the merge, so we copy
499 # the remaining elements of a and then the remaining elements of b.
500 assert a.len >= 0 and b.len >= 0
501 for p in xrange(a.base + a.len - 1, a.base - 1, -1):
502 dest -= 1
503 self.setitem(dest, a.getitem(p))
504 for p in xrange(b.base + b.len - 1, b.base - 1, -1):
505 dest -= 1
506 self.setitem(dest, b.getitem(p))
507
508 # Merge the two runs at stack indices i and i+1.
509
510 def merge_at(self, i):
511 a = self.pending[i]
512 b = self.pending[i+1]
513 assert a.len > 0 and b.len > 0
514 assert a.base + a.len == b.base
515
516 # Record the length of the combined runs and remove the run b
517 self.pending[i] = ListSlice(self.list, a.base, a.len + b.len)
518 del self.pending[i+1]
519
520 # Where does b start in a? Elements in a before that can be
521 # ignored (already in place).
522 k = self.gallop(b.getitem(b.base), a, hint=0, rightmost=True)
523 a.advance(k)
524 if a.len == 0:
525 return
526
527 # Where does a end in b? Elements in b after that can be
528 # ignored (already in place).
529 b.len = self.gallop(a.getitem(a.base+a.len-1), b, hint=b.len-1,
530 rightmost=False)
531 if b.len == 0:
532 return
533
534 # Merge what remains of the runs. The direction is chosen to
535 # minimize the temporary storage needed.
536 if a.len <= b.len:
537 self.merge_lo(a, b)
538 else:
539 self.merge_hi(a, b)
540
541 def found_new_run(self, run):
542 """
543 The next run has been identified.
544 If there's already a run on the stack, apply the "powersort" merge strategy:
545 compute the topmost run's "power" (depth in a conceptual binary merge tree)
546 and merge adjacent runs on the stack with greater power. See listsort.txt
547 for more info.
548
549 It's the caller's responsibilty to push the new run on the stack when this
550 returns.
551
552 See listsort.txt for more info.
553 """
554
555 p = self.pending
556 if p:
557 s1 = p[-1].base
558 n1 = p[-1].len
559 power = powerloop(s1, n1, run.len, self.listlength)
560 while len(p) > 1 and p[-2].power > power:
561 self.merge_at(-2)
562 assert len(p) < 2 or p[-2].power < power
563 p[-1].power = power;
564
565 def merge_force_collapse(self):
566 p = self.pending
567 while len(p) > 1:
568 n = -2
569 if len(p) >= 3 and p[-3].len < p[-1].len:
570 n = -3
571 self.merge_at(n)
572
573 merge_compute_minrun = staticmethod(merge_compute_minrun)
574
575 # ____________________________________________________________
576 # Entry point.
577
578 def sort(self):
579 if self.listlength < 2:
580 return
581 remaining = ListSlice(self.list, 0, self.listlength)
582
583 # March over the array once, left to right, finding natural runs,
584 # and extending short natural runs to minrun elements.
585 self.merge_init()
586 minrun = self.merge_compute_minrun(remaining.len)
587
588 while remaining.len > 0:
589 # Identify next run.
590 run = ListSlice(remaining.list, remaining.base, remaining.len)
591 descending = self.count_run(remaining, run)
592 if descending:
593 run.reverse()
594 # If short, extend to min(minrun, nremaining).
595 if run.len < minrun:
596 sorted = run.len
597 run.len = min(minrun, remaining.len)
598 self.binarysort(run, sorted)
599 # maybe merge (but never the newest)
600 self.found_new_run(run)
601 # Push run onto pending-runs stack
602 self.pending.append(run)
603 # Advance remaining past this run.
604 remaining.advance(run.len)
605
606 assert remaining.base == self.listlength
607
608 self.merge_force_collapse()
609 assert len(self.pending) == 1
610 assert self.pending[0].base == 0
611 assert self.pending[0].len == self.listlength
612
613 class ListSlice:
614 "A sublist of a list."
615
616 def __init__(self, list, base, len):
617 self.list = list
618 self.base = base
619 self.len = len
620
621 def __repr__(self):
622 return "<ListSlice base=%s len=%s %s>" % (
623 self.base, self.len, self.list[self.base: self.base+self.len])
624
625 def copyitems(self, sorter):
626 "Make a copy of the slice of the original list."
627 if sorter.scratch_list is None or self.len > length(sorter.scratch_list):
628 listlength = length(self.list)
629 scratchsize = min((listlength + 1) // 2, 256)
630 if self.len > scratchsize:
631 scratchsize = self.len
632 start = self.base
633 stop = self.base + scratchsize
634 if stop > listlength:
635 stop = listlength
636 assert 0 <= start <= stop # annotator hint
637 scratch_list = sorter.scratch_list = getitem_slice(self.list, start, stop)
638 else:
639 scratch_list = sorter.scratch_list
640 base = self.base
641 for i in range(self.len):
642 setitem(scratch_list, i, getitem(self.list, base + i))
643 self.list = scratch_list
644 self.base = 0
645
646 def advance(self, n):
647 self.base += n
648 self.len -= n
649
650 def getitem(self, item):
651 return getitem(self.list, item)
652
653 def setitem(self, item, value):
654 setitem(self.list, item, value)
655
656 def popleft(self):
657 result = getitem(self.list, self.base)
658 self.base += 1
659 self.len -= 1
660 return result
661
662 def popright(self):
663 self.len -= 1
664 return getitem(self.list, self.base + self.len)
665
666 def reverse(self):
667 "Reverse the slice in-place."
668 list = self.list
669 lo = self.base
670 hi = lo + self.len - 1
671 while lo < hi:
672 list_hi = getitem(list, hi)
673 list_lo = getitem(list, lo)
674 setitem(list, lo, list_hi)
675 setitem(list, hi, list_lo)
676 lo += 1
677 hi -= 1
678 return TimSort
679
680 TimSort = make_timsort_class() #backward compatible interface