Debian Codegraph @

stdlib/generic/go1_21_slices.go.txt

raw
1 // Copyright 2021 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package slices defines various functions useful with slices of any type.
6 package slices
7
8 import (
9 "cmp"
10 "math/bits"
11 // "unsafe" // FIXME(marc): better handle special dependencies in generics.
12 )
13
14 // Equal reports whether two slices are equal: the same length and all
15 // elements equal. If the lengths are different, Equal returns false.
16 // Otherwise, the elements are compared in increasing index order, and the
17 // comparison stops at the first unequal pair.
18 // Floating point NaNs are not considered equal.
19 func Equal[S ~[]E, E comparable](s1, s2 S) bool {
20 if len(s1) != len(s2) {
21 return false
22 }
23 for i := range s1 {
24 if s1[i] != s2[i] {
25 return false
26 }
27 }
28 return true
29 }
30
31 // EqualFunc reports whether two slices are equal using an equality
32 // function on each pair of elements. If the lengths are different,
33 // EqualFunc returns false. Otherwise, the elements are compared in
34 // increasing index order, and the comparison stops at the first index
35 // for which eq returns false.
36 func EqualFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, eq func(E1, E2) bool) bool {
37 if len(s1) != len(s2) {
38 return false
39 }
40 for i, v1 := range s1 {
41 v2 := s2[i]
42 if !eq(v1, v2) {
43 return false
44 }
45 }
46 return true
47 }
48
49 // Compare compares the elements of s1 and s2, using [cmp.Compare] on each pair
50 // of elements. The elements are compared sequentially, starting at index 0,
51 // until one element is not equal to the other.
52 // The result of comparing the first non-matching elements is returned.
53 // If both slices are equal until one of them ends, the shorter slice is
54 // considered less than the longer one.
55 // The result is 0 if s1 == s2, -1 if s1 < s2, and +1 if s1 > s2.
56 func Compare[S ~[]E, E cmp.Ordered](s1, s2 S) int {
57 for i, v1 := range s1 {
58 if i >= len(s2) {
59 return +1
60 }
61 v2 := s2[i]
62 if c := cmp.Compare(v1, v2); c != 0 {
63 return c
64 }
65 }
66 if len(s1) < len(s2) {
67 return -1
68 }
69 return 0
70 }
71
72 // CompareFunc is like [Compare] but uses a custom comparison function on each
73 // pair of elements.
74 // The result is the first non-zero result of cmp; if cmp always
75 // returns 0 the result is 0 if len(s1) == len(s2), -1 if len(s1) < len(s2),
76 // and +1 if len(s1) > len(s2).
77 func CompareFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, cmp func(E1, E2) int) int {
78 for i, v1 := range s1 {
79 if i >= len(s2) {
80 return +1
81 }
82 v2 := s2[i]
83 if c := cmp(v1, v2); c != 0 {
84 return c
85 }
86 }
87 if len(s1) < len(s2) {
88 return -1
89 }
90 return 0
91 }
92
93 // Index returns the index of the first occurrence of v in s,
94 // or -1 if not present.
95 func Index[S ~[]E, E comparable](s S, v E) int {
96 for i := range s {
97 if v == s[i] {
98 return i
99 }
100 }
101 return -1
102 }
103
104 // IndexFunc returns the first index i satisfying f(s[i]),
105 // or -1 if none do.
106 func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int {
107 for i := range s {
108 if f(s[i]) {
109 return i
110 }
111 }
112 return -1
113 }
114
115 // Contains reports whether v is present in s.
116 func Contains[S ~[]E, E comparable](s S, v E) bool {
117 return Index(s, v) >= 0
118 }
119
120 // ContainsFunc reports whether at least one
121 // element e of s satisfies f(e).
122 func ContainsFunc[S ~[]E, E any](s S, f func(E) bool) bool {
123 return IndexFunc(s, f) >= 0
124 }
125
126 // Insert inserts the values v... into s at index i,
127 // returning the modified slice.
128 // The elements at s[i:] are shifted up to make room.
129 // In the returned slice r, r[i] == v[0],
130 // and r[i+len(v)] == value originally at r[i].
131 // Insert panics if i is out of range.
132 // This function is O(len(s) + len(v)).
133 func Insert[S ~[]E, E any](s S, i int, v ...E) S {
134 m := len(v)
135 if m == 0 {
136 return s
137 }
138 n := len(s)
139 if i == n {
140 return append(s, v...)
141 }
142 if n+m > cap(s) {
143 // Use append rather than make so that we bump the size of
144 // the slice up to the next storage class.
145 // This is what Grow does but we don't call Grow because
146 // that might copy the values twice.
147 s2 := append(s[:i], make(S, n+m-i)...)
148 copy(s2[i:], v)
149 copy(s2[i+m:], s[i:])
150 return s2
151 }
152 s = s[:n+m]
153
154 // before:
155 // s: aaaaaaaabbbbccccccccdddd
156 // ^ ^ ^ ^
157 // i i+m n n+m
158 // after:
159 // s: aaaaaaaavvvvbbbbcccccccc
160 // ^ ^ ^ ^
161 // i i+m n n+m
162 //
163 // a are the values that don't move in s.
164 // v are the values copied in from v.
165 // b and c are the values from s that are shifted up in index.
166 // d are the values that get overwritten, never to be seen again.
167
168 if !overlaps(v, s[i+m:]) {
169 // Easy case - v does not overlap either the c or d regions.
170 // (It might be in some of a or b, or elsewhere entirely.)
171 // The data we copy up doesn't write to v at all, so just do it.
172
173 copy(s[i+m:], s[i:])
174
175 // Now we have
176 // s: aaaaaaaabbbbbbbbcccccccc
177 // ^ ^ ^ ^
178 // i i+m n n+m
179 // Note the b values are duplicated.
180
181 copy(s[i:], v)
182
183 // Now we have
184 // s: aaaaaaaavvvvbbbbcccccccc
185 // ^ ^ ^ ^
186 // i i+m n n+m
187 // That's the result we want.
188 return s
189 }
190
191 // The hard case - v overlaps c or d. We can't just shift up
192 // the data because we'd move or clobber the values we're trying
193 // to insert.
194 // So instead, write v on top of d, then rotate.
195 copy(s[n:], v)
196
197 // Now we have
198 // s: aaaaaaaabbbbccccccccvvvv
199 // ^ ^ ^ ^
200 // i i+m n n+m
201
202 rotateRight(s[i:], m)
203
204 // Now we have
205 // s: aaaaaaaavvvvbbbbcccccccc
206 // ^ ^ ^ ^
207 // i i+m n n+m
208 // That's the result we want.
209 return s
210 }
211
212 // Delete removes the elements s[i:j] from s, returning the modified slice.
213 // Delete panics if s[i:j] is not a valid slice of s.
214 // Delete is O(len(s)-j), so if many items must be deleted, it is better to
215 // make a single call deleting them all together than to delete one at a time.
216 // Delete might not modify the elements s[len(s)-(j-i):len(s)]. If those
217 // elements contain pointers you might consider zeroing those elements so that
218 // objects they reference can be garbage collected.
219 func Delete[S ~[]E, E any](s S, i, j int) S {
220 _ = s[i:j] // bounds check
221
222 return append(s[:i], s[j:]...)
223 }
224
225 // DeleteFunc removes any elements from s for which del returns true,
226 // returning the modified slice.
227 // When DeleteFunc removes m elements, it might not modify the elements
228 // s[len(s)-m:len(s)]. If those elements contain pointers you might consider
229 // zeroing those elements so that objects they reference can be garbage
230 // collected.
231 func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S {
232 // Don't start copying elements until we find one to delete.
233 for i, v := range s {
234 if del(v) {
235 j := i
236 for i++; i < len(s); i++ {
237 v = s[i]
238 if !del(v) {
239 s[j] = v
240 j++
241 }
242 }
243 return s[:j]
244 }
245 }
246 return s
247 }
248
249 // Replace replaces the elements s[i:j] by the given v, and returns the
250 // modified slice. Replace panics if s[i:j] is not a valid slice of s.
251 func Replace[S ~[]E, E any](s S, i, j int, v ...E) S {
252 _ = s[i:j] // verify that i:j is a valid subslice
253
254 if i == j {
255 return Insert(s, i, v...)
256 }
257 if j == len(s) {
258 return append(s[:i], v...)
259 }
260
261 tot := len(s[:i]) + len(v) + len(s[j:])
262 if tot > cap(s) {
263 // Too big to fit, allocate and copy over.
264 s2 := append(s[:i], make(S, tot-i)...) // See Insert
265 copy(s2[i:], v)
266 copy(s2[i+len(v):], s[j:])
267 return s2
268 }
269
270 r := s[:tot]
271
272 if i+len(v) <= j {
273 // Easy, as v fits in the deleted portion.
274 copy(r[i:], v)
275 if i+len(v) != j {
276 copy(r[i+len(v):], s[j:])
277 }
278 return r
279 }
280
281 // We are expanding (v is bigger than j-i).
282 // The situation is something like this:
283 // (example has i=4,j=8,len(s)=16,len(v)=6)
284 // s: aaaaxxxxbbbbbbbbyy
285 // ^ ^ ^ ^
286 // i j len(s) tot
287 // a: prefix of s
288 // x: deleted range
289 // b: more of s
290 // y: area to expand into
291
292 if !overlaps(r[i+len(v):], v) {
293 // Easy, as v is not clobbered by the first copy.
294 copy(r[i+len(v):], s[j:])
295 copy(r[i:], v)
296 return r
297 }
298
299 // This is a situation where we don't have a single place to which
300 // we can copy v. Parts of it need to go to two different places.
301 // We want to copy the prefix of v into y and the suffix into x, then
302 // rotate |y| spots to the right.
303 //
304 // v[2:] v[:2]
305 // | |
306 // s: aaaavvvvbbbbbbbbvv
307 // ^ ^ ^ ^
308 // i j len(s) tot
309 //
310 // If either of those two destinations don't alias v, then we're good.
311 y := len(v) - (j - i) // length of y portion
312
313 if !overlaps(r[i:j], v) {
314 copy(r[i:j], v[y:])
315 copy(r[len(s):], v[:y])
316 rotateRight(r[i:], y)
317 return r
318 }
319 if !overlaps(r[len(s):], v) {
320 copy(r[len(s):], v[:y])
321 copy(r[i:j], v[y:])
322 rotateRight(r[i:], y)
323 return r
324 }
325
326 // Now we know that v overlaps both x and y.
327 // That means that the entirety of b is *inside* v.
328 // So we don't need to preserve b at all; instead we
329 // can copy v first, then copy the b part of v out of
330 // v to the right destination.
331 k := startIdx(v, s[j:])
332 copy(r[i:], v)
333 copy(r[i+len(v):], r[i+k:])
334 return r
335 }
336
337 // Clone returns a copy of the slice.
338 // The elements are copied using assignment, so this is a shallow clone.
339 func Clone[S ~[]E, E any](s S) S {
340 // Preserve nil in case it matters.
341 if s == nil {
342 return nil
343 }
344 return append(S([]E{}), s...)
345 }
346
347 // Compact replaces consecutive runs of equal elements with a single copy.
348 // This is like the uniq command found on Unix.
349 // Compact modifies the contents of the slice s and returns the modified slice,
350 // which may have a smaller length.
351 // When Compact discards m elements in total, it might not modify the elements
352 // s[len(s)-m:len(s)]. If those elements contain pointers you might consider
353 // zeroing those elements so that objects they reference can be garbage collected.
354 func Compact[S ~[]E, E comparable](s S) S {
355 if len(s) < 2 {
356 return s
357 }
358 i := 1
359 for k := 1; k < len(s); k++ {
360 if s[k] != s[k-1] {
361 if i != k {
362 s[i] = s[k]
363 }
364 i++
365 }
366 }
367 return s[:i]
368 }
369
370 // CompactFunc is like [Compact] but uses an equality function to compare elements.
371 // For runs of elements that compare equal, CompactFunc keeps the first one.
372 func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S {
373 if len(s) < 2 {
374 return s
375 }
376 i := 1
377 for k := 1; k < len(s); k++ {
378 if !eq(s[k], s[k-1]) {
379 if i != k {
380 s[i] = s[k]
381 }
382 i++
383 }
384 }
385 return s[:i]
386 }
387
388 // Grow increases the slice's capacity, if necessary, to guarantee space for
389 // another n elements. After Grow(n), at least n elements can be appended
390 // to the slice without another allocation. If n is negative or too large to
391 // allocate the memory, Grow panics.
392 func Grow[S ~[]E, E any](s S, n int) S {
393 if n < 0 {
394 panic("cannot be negative")
395 }
396 if n -= cap(s) - len(s); n > 0 {
397 s = append(s[:cap(s)], make([]E, n)...)[:len(s)]
398 }
399 return s
400 }
401
402 // Clip removes unused capacity from the slice, returning s[:len(s):len(s)].
403 func Clip[S ~[]E, E any](s S) S {
404 return s[:len(s):len(s)]
405 }
406
407 // Rotation algorithm explanation:
408 //
409 // rotate left by 2
410 // start with
411 // 0123456789
412 // split up like this
413 // 01 234567 89
414 // swap first 2 and last 2
415 // 89 234567 01
416 // join first parts
417 // 89234567 01
418 // recursively rotate first left part by 2
419 // 23456789 01
420 // join at the end
421 // 2345678901
422 //
423 // rotate left by 8
424 // start with
425 // 0123456789
426 // split up like this
427 // 01 234567 89
428 // swap first 2 and last 2
429 // 89 234567 01
430 // join last parts
431 // 89 23456701
432 // recursively rotate second part left by 6
433 // 89 01234567
434 // join at the end
435 // 8901234567
436
437 // TODO: There are other rotate algorithms.
438 // This algorithm has the desirable property that it moves each element exactly twice.
439 // The triple-reverse algorithm is simpler and more cache friendly, but takes more writes.
440 // The follow-cycles algorithm can be 1-write but it is not very cache friendly.
441
442 // rotateLeft rotates b left by n spaces.
443 // s_final[i] = s_orig[i+r], wrapping around.
444 func rotateLeft[E any](s []E, r int) {
445 for r != 0 && r != len(s) {
446 if r*2 <= len(s) {
447 swap(s[:r], s[len(s)-r:])
448 s = s[:len(s)-r]
449 } else {
450 swap(s[:len(s)-r], s[r:])
451 s, r = s[len(s)-r:], r*2-len(s)
452 }
453 }
454 }
455 func rotateRight[E any](s []E, r int) {
456 rotateLeft(s, len(s)-r)
457 }
458
459 // swap swaps the contents of x and y. x and y must be equal length and disjoint.
460 func swap[E any](x, y []E) {
461 for i := 0; i < len(x); i++ {
462 x[i], y[i] = y[i], x[i]
463 }
464 }
465
466 // overlaps reports whether the memory ranges a[0:len(a)] and b[0:len(b)] overlap.
467 func overlaps[E any](a, b []E) bool {
468 if len(a) == 0 || len(b) == 0 {
469 return false
470 }
471 elemSize := unsafe.Sizeof(a[0])
472 if elemSize == 0 {
473 return false
474 }
475 // TODO: use a runtime/unsafe facility once one becomes available. See issue 12445.
476 // Also see crypto/internal/alias/alias.go:AnyOverlap
477 return uintptr(unsafe.Pointer(&a[0])) <= uintptr(unsafe.Pointer(&b[len(b)-1]))+(elemSize-1) &&
478 uintptr(unsafe.Pointer(&b[0])) <= uintptr(unsafe.Pointer(&a[len(a)-1]))+(elemSize-1)
479 }
480
481 // startIdx returns the index in haystack where the needle starts.
482 // prerequisite: the needle must be aliased entirely inside the haystack.
483 func startIdx[E any](haystack, needle []E) int {
484 p := &needle[0]
485 for i := range haystack {
486 if p == &haystack[i] {
487 return i
488 }
489 }
490 // TODO: what if the overlap is by a non-integral number of Es?
491 panic("needle not found")
492 }
493
494 // Reverse reverses the elements of the slice in place.
495 func Reverse[S ~[]E, E any](s S) {
496 for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
497 s[i], s[j] = s[j], s[i]
498 }
499 }
500 // Copyright 2023 The Go Authors. All rights reserved.
501 // Use of this source code is governed by a BSD-style
502 // license that can be found in the LICENSE file.
503
504 //package slices
505
506 //import (
507 // "cmp"
508 // "math/bits"
509 //)
510
511 // Sort sorts a slice of any ordered type in ascending order.
512 // When sorting floating-point numbers, NaNs are ordered before other values.
513 func Sort[S ~[]E, E cmp.Ordered](x S) {
514 n := len(x)
515 pdqsortOrdered(x, 0, n, bits.Len(uint(n)))
516 }
517
518 // SortFunc sorts the slice x in ascending order as determined by the cmp
519 // function. This sort is not guaranteed to be stable.
520 // cmp(a, b) should return a negative number when a < b, a positive number when
521 // a > b and zero when a == b.
522 //
523 // SortFunc requires that cmp is a strict weak ordering.
524 // See https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings.
525 func SortFunc[S ~[]E, E any](x S, cmp func(a, b E) int) {
526 n := len(x)
527 pdqsortCmpFunc(x, 0, n, bits.Len(uint(n)), cmp)
528 }
529
530 // SortStableFunc sorts the slice x while keeping the original order of equal
531 // elements, using cmp to compare elements in the same way as [SortFunc].
532 func SortStableFunc[S ~[]E, E any](x S, cmp func(a, b E) int) {
533 stableCmpFunc(x, len(x), cmp)
534 }
535
536 // IsSorted reports whether x is sorted in ascending order.
537 func IsSorted[S ~[]E, E cmp.Ordered](x S) bool {
538 for i := len(x) - 1; i > 0; i-- {
539 if cmp.Less(x[i], x[i-1]) {
540 return false
541 }
542 }
543 return true
544 }
545
546 // IsSortedFunc reports whether x is sorted in ascending order, with cmp as the
547 // comparison function as defined by [SortFunc].
548 func IsSortedFunc[S ~[]E, E any](x S, cmp func(a, b E) int) bool {
549 for i := len(x) - 1; i > 0; i-- {
550 if cmp(x[i], x[i-1]) < 0 {
551 return false
552 }
553 }
554 return true
555 }
556
557 // Min returns the minimal value in x. It panics if x is empty.
558 // For floating-point numbers, Min propagates NaNs (any NaN value in x
559 // forces the output to be NaN).
560 func Min[S ~[]E, E cmp.Ordered](x S) E {
561 if len(x) < 1 {
562 panic("slices.Min: empty list")
563 }
564 m := x[0]
565 for i := 1; i < len(x); i++ {
566 m = min(m, x[i])
567 }
568 return m
569 }
570
571 // MinFunc returns the minimal value in x, using cmp to compare elements.
572 // It panics if x is empty. If there is more than one minimal element
573 // according to the cmp function, MinFunc returns the first one.
574 func MinFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E {
575 if len(x) < 1 {
576 panic("slices.MinFunc: empty list")
577 }
578 m := x[0]
579 for i := 1; i < len(x); i++ {
580 if cmp(x[i], m) < 0 {
581 m = x[i]
582 }
583 }
584 return m
585 }
586
587 // Max returns the maximal value in x. It panics if x is empty.
588 // For floating-point E, Max propagates NaNs (any NaN value in x
589 // forces the output to be NaN).
590 func Max[S ~[]E, E cmp.Ordered](x S) E {
591 if len(x) < 1 {
592 panic("slices.Max: empty list")
593 }
594 m := x[0]
595 for i := 1; i < len(x); i++ {
596 m = max(m, x[i])
597 }
598 return m
599 }
600
601 // MaxFunc returns the maximal value in x, using cmp to compare elements.
602 // It panics if x is empty. If there is more than one maximal element
603 // according to the cmp function, MaxFunc returns the first one.
604 func MaxFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E {
605 if len(x) < 1 {
606 panic("slices.MaxFunc: empty list")
607 }
608 m := x[0]
609 for i := 1; i < len(x); i++ {
610 if cmp(x[i], m) > 0 {
611 m = x[i]
612 }
613 }
614 return m
615 }
616
617 // BinarySearch searches for target in a sorted slice and returns the position
618 // where target is found, or the position where target would appear in the
619 // sort order; it also returns a bool saying whether the target is really found
620 // in the slice. The slice must be sorted in increasing order.
621 func BinarySearch[S ~[]E, E cmp.Ordered](x S, target E) (int, bool) {
622 // Inlining is faster than calling BinarySearchFunc with a lambda.
623 n := len(x)
624 // Define x[-1] < target and x[n] >= target.
625 // Invariant: x[i-1] < target, x[j] >= target.
626 i, j := 0, n
627 for i < j {
628 h := int(uint(i+j) >> 1) // avoid overflow when computing h
629 // i ≤ h < j
630 if cmp.Less(x[h], target) {
631 i = h + 1 // preserves x[i-1] < target
632 } else {
633 j = h // preserves x[j] >= target
634 }
635 }
636 // i == j, x[i-1] < target, and x[j] (= x[i]) >= target => answer is i.
637 return i, i < n && (x[i] == target || (isNaN(x[i]) && isNaN(target)))
638 }
639
640 // BinarySearchFunc works like [BinarySearch], but uses a custom comparison
641 // function. The slice must be sorted in increasing order, where "increasing"
642 // is defined by cmp. cmp should return 0 if the slice element matches
643 // the target, a negative number if the slice element precedes the target,
644 // or a positive number if the slice element follows the target.
645 // cmp must implement the same ordering as the slice, such that if
646 // cmp(a, t) < 0 and cmp(b, t) >= 0, then a must precede b in the slice.
647 func BinarySearchFunc[S ~[]E, E, T any](x S, target T, cmp func(E, T) int) (int, bool) {
648 n := len(x)
649 // Define cmp(x[-1], target) < 0 and cmp(x[n], target) >= 0 .
650 // Invariant: cmp(x[i - 1], target) < 0, cmp(x[j], target) >= 0.
651 i, j := 0, n
652 for i < j {
653 h := int(uint(i+j) >> 1) // avoid overflow when computing h
654 // i ≤ h < j
655 if cmp(x[h], target) < 0 {
656 i = h + 1 // preserves cmp(x[i - 1], target) < 0
657 } else {
658 j = h // preserves cmp(x[j], target) >= 0
659 }
660 }
661 // i == j, cmp(x[i-1], target) < 0, and cmp(x[j], target) (= cmp(x[i], target)) >= 0 => answer is i.
662 return i, i < n && cmp(x[i], target) == 0
663 }
664
665 type sortedHint int // hint for pdqsort when choosing the pivot
666
667 const (
668 unknownHint sortedHint = iota
669 increasingHint
670 decreasingHint
671 )
672
673 // xorshift paper: https://www.jstatsoft.org/article/view/v008i14/xorshift.pdf
674 type xorshift uint64
675
676 func (r *xorshift) Next() uint64 {
677 *r ^= *r << 13
678 *r ^= *r >> 17
679 *r ^= *r << 5
680 return uint64(*r)
681 }
682
683 func nextPowerOfTwo(length int) uint {
684 return 1 << bits.Len(uint(length))
685 }
686
687 // isNaN reports whether x is a NaN without requiring the math package.
688 // This will always return false if T is not floating-point.
689 func isNaN[T cmp.Ordered](x T) bool {
690 return x != x
691 }
692 // Code generated by gen_sort_variants.go; DO NOT EDIT.
693
694 // Copyright 2022 The Go Authors. All rights reserved.
695 // Use of this source code is governed by a BSD-style
696 // license that can be found in the LICENSE file.
697
698 // package slices
699
700 // insertionSortCmpFunc sorts data[a:b] using insertion sort.
701 func insertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
702 for i := a + 1; i < b; i++ {
703 for j := i; j > a && (cmp(data[j], data[j-1]) < 0); j-- {
704 data[j], data[j-1] = data[j-1], data[j]
705 }
706 }
707 }
708
709 // siftDownCmpFunc implements the heap property on data[lo:hi].
710 // first is an offset into the array where the root of the heap lies.
711 func siftDownCmpFunc[E any](data []E, lo, hi, first int, cmp func(a, b E) int) {
712 root := lo
713 for {
714 child := 2*root + 1
715 if child >= hi {
716 break
717 }
718 if child+1 < hi && (cmp(data[first+child], data[first+child+1]) < 0) {
719 child++
720 }
721 if !(cmp(data[first+root], data[first+child]) < 0) {
722 return
723 }
724 data[first+root], data[first+child] = data[first+child], data[first+root]
725 root = child
726 }
727 }
728
729 func heapSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
730 first := a
731 lo := 0
732 hi := b - a
733
734 // Build heap with greatest element at top.
735 for i := (hi - 1) / 2; i >= 0; i-- {
736 siftDownCmpFunc(data, i, hi, first, cmp)
737 }
738
739 // Pop elements, largest first, into end of data.
740 for i := hi - 1; i >= 0; i-- {
741 data[first], data[first+i] = data[first+i], data[first]
742 siftDownCmpFunc(data, lo, i, first, cmp)
743 }
744 }
745
746 // pdqsortCmpFunc sorts data[a:b].
747 // The algorithm based on pattern-defeating quicksort(pdqsort), but without the optimizations from BlockQuicksort.
748 // pdqsort paper: https://arxiv.org/pdf/2106.05123.pdf
749 // C++ implementation: https://github.com/orlp/pdqsort
750 // Rust implementation: https://docs.rs/pdqsort/latest/pdqsort/
751 // limit is the number of allowed bad (very unbalanced) pivots before falling back to heapsort.
752 func pdqsortCmpFunc[E any](data []E, a, b, limit int, cmp func(a, b E) int) {
753 const maxInsertion = 12
754
755 var (
756 wasBalanced = true // whether the last partitioning was reasonably balanced
757 wasPartitioned = true // whether the slice was already partitioned
758 )
759
760 for {
761 length := b - a
762
763 if length <= maxInsertion {
764 insertionSortCmpFunc(data, a, b, cmp)
765 return
766 }
767
768 // Fall back to heapsort if too many bad choices were made.
769 if limit == 0 {
770 heapSortCmpFunc(data, a, b, cmp)
771 return
772 }
773
774 // If the last partitioning was imbalanced, we need to breaking patterns.
775 if !wasBalanced {
776 breakPatternsCmpFunc(data, a, b, cmp)
777 limit--
778 }
779
780 pivot, hint := choosePivotCmpFunc(data, a, b, cmp)
781 if hint == decreasingHint {
782 reverseRangeCmpFunc(data, a, b, cmp)
783 // The chosen pivot was pivot-a elements after the start of the array.
784 // After reversing it is pivot-a elements before the end of the array.
785 // The idea came from Rust's implementation.
786 pivot = (b - 1) - (pivot - a)
787 hint = increasingHint
788 }
789
790 // The slice is likely already sorted.
791 if wasBalanced && wasPartitioned && hint == increasingHint {
792 if partialInsertionSortCmpFunc(data, a, b, cmp) {
793 return
794 }
795 }
796
797 // Probably the slice contains many duplicate elements, partition the slice into
798 // elements equal to and elements greater than the pivot.
799 if a > 0 && !(cmp(data[a-1], data[pivot]) < 0) {
800 mid := partitionEqualCmpFunc(data, a, b, pivot, cmp)
801 a = mid
802 continue
803 }
804
805 mid, alreadyPartitioned := partitionCmpFunc(data, a, b, pivot, cmp)
806 wasPartitioned = alreadyPartitioned
807
808 leftLen, rightLen := mid-a, b-mid
809 balanceThreshold := length / 8
810 if leftLen < rightLen {
811 wasBalanced = leftLen >= balanceThreshold
812 pdqsortCmpFunc(data, a, mid, limit, cmp)
813 a = mid + 1
814 } else {
815 wasBalanced = rightLen >= balanceThreshold
816 pdqsortCmpFunc(data, mid+1, b, limit, cmp)
817 b = mid
818 }
819 }
820 }
821
822 // partitionCmpFunc does one quicksort partition.
823 // Let p = data[pivot]
824 // Moves elements in data[a:b] around, so that data[i]<p and data[j]>=p for i<newpivot and j>newpivot.
825 // On return, data[newpivot] = p
826 func partitionCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (newpivot int, alreadyPartitioned bool) {
827 data[a], data[pivot] = data[pivot], data[a]
828 i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned
829
830 for i <= j && (cmp(data[i], data[a]) < 0) {
831 i++
832 }
833 for i <= j && !(cmp(data[j], data[a]) < 0) {
834 j--
835 }
836 if i > j {
837 data[j], data[a] = data[a], data[j]
838 return j, true
839 }
840 data[i], data[j] = data[j], data[i]
841 i++
842 j--
843
844 for {
845 for i <= j && (cmp(data[i], data[a]) < 0) {
846 i++
847 }
848 for i <= j && !(cmp(data[j], data[a]) < 0) {
849 j--
850 }
851 if i > j {
852 break
853 }
854 data[i], data[j] = data[j], data[i]
855 i++
856 j--
857 }
858 data[j], data[a] = data[a], data[j]
859 return j, false
860 }
861
862 // partitionEqualCmpFunc partitions data[a:b] into elements equal to data[pivot] followed by elements greater than data[pivot].
863 // It assumed that data[a:b] does not contain elements smaller than the data[pivot].
864 func partitionEqualCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (newpivot int) {
865 data[a], data[pivot] = data[pivot], data[a]
866 i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned
867
868 for {
869 for i <= j && !(cmp(data[a], data[i]) < 0) {
870 i++
871 }
872 for i <= j && (cmp(data[a], data[j]) < 0) {
873 j--
874 }
875 if i > j {
876 break
877 }
878 data[i], data[j] = data[j], data[i]
879 i++
880 j--
881 }
882 return i
883 }
884
885 // partialInsertionSortCmpFunc partially sorts a slice, returns true if the slice is sorted at the end.
886 func partialInsertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) bool {
887 const (
888 maxSteps = 5 // maximum number of adjacent out-of-order pairs that will get shifted
889 shortestShifting = 50 // don't shift any elements on short arrays
890 )
891 i := a + 1
892 for j := 0; j < maxSteps; j++ {
893 for i < b && !(cmp(data[i], data[i-1]) < 0) {
894 i++
895 }
896
897 if i == b {
898 return true
899 }
900
901 if b-a < shortestShifting {
902 return false
903 }
904
905 data[i], data[i-1] = data[i-1], data[i]
906
907 // Shift the smaller one to the left.
908 if i-a >= 2 {
909 for j := i - 1; j >= 1; j-- {
910 if !(cmp(data[j], data[j-1]) < 0) {
911 break
912 }
913 data[j], data[j-1] = data[j-1], data[j]
914 }
915 }
916 // Shift the greater one to the right.
917 if b-i >= 2 {
918 for j := i + 1; j < b; j++ {
919 if !(cmp(data[j], data[j-1]) < 0) {
920 break
921 }
922 data[j], data[j-1] = data[j-1], data[j]
923 }
924 }
925 }
926 return false
927 }
928
929 // breakPatternsCmpFunc scatters some elements around in an attempt to break some patterns
930 // that might cause imbalanced partitions in quicksort.
931 func breakPatternsCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
932 length := b - a
933 if length >= 8 {
934 random := xorshift(length)
935 modulus := nextPowerOfTwo(length)
936
937 for idx := a + (length/4)*2 - 1; idx <= a+(length/4)*2+1; idx++ {
938 other := int(uint(random.Next()) & (modulus - 1))
939 if other >= length {
940 other -= length
941 }
942 data[idx], data[a+other] = data[a+other], data[idx]
943 }
944 }
945 }
946
947 // choosePivotCmpFunc chooses a pivot in data[a:b].
948 //
949 // [0,8): chooses a static pivot.
950 // [8,shortestNinther): uses the simple median-of-three method.
951 // [shortestNinther,∞): uses the Tukey ninther method.
952 func choosePivotCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) (pivot int, hint sortedHint) {
953 const (
954 shortestNinther = 50
955 maxSwaps = 4 * 3
956 )
957
958 l := b - a
959
960 var (
961 swaps int
962 i = a + l/4*1
963 j = a + l/4*2
964 k = a + l/4*3
965 )
966
967 if l >= 8 {
968 if l >= shortestNinther {
969 // Tukey ninther method, the idea came from Rust's implementation.
970 i = medianAdjacentCmpFunc(data, i, &swaps, cmp)
971 j = medianAdjacentCmpFunc(data, j, &swaps, cmp)
972 k = medianAdjacentCmpFunc(data, k, &swaps, cmp)
973 }
974 // Find the median among i, j, k and stores it into j.
975 j = medianCmpFunc(data, i, j, k, &swaps, cmp)
976 }
977
978 switch swaps {
979 case 0:
980 return j, increasingHint
981 case maxSwaps:
982 return j, decreasingHint
983 default:
984 return j, unknownHint
985 }
986 }
987
988 // order2CmpFunc returns x,y where data[x] <= data[y], where x,y=a,b or x,y=b,a.
989 func order2CmpFunc[E any](data []E, a, b int, swaps *int, cmp func(a, b E) int) (int, int) {
990 if cmp(data[b], data[a]) < 0 {
991 *swaps++
992 return b, a
993 }
994 return a, b
995 }
996
997 // medianCmpFunc returns x where data[x] is the median of data[a],data[b],data[c], where x is a, b, or c.
998 func medianCmpFunc[E any](data []E, a, b, c int, swaps *int, cmp func(a, b E) int) int {
999 a, b = order2CmpFunc(data, a, b, swaps, cmp)
1000 b, c = order2CmpFunc(data, b, c, swaps, cmp)
1001 a, b = order2CmpFunc(data, a, b, swaps, cmp)
1002 return b
1003 }
1004
1005 // medianAdjacentCmpFunc finds the median of data[a - 1], data[a], data[a + 1] and stores the index into a.
1006 func medianAdjacentCmpFunc[E any](data []E, a int, swaps *int, cmp func(a, b E) int) int {
1007 return medianCmpFunc(data, a-1, a, a+1, swaps, cmp)
1008 }
1009
1010 func reverseRangeCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
1011 i := a
1012 j := b - 1
1013 for i < j {
1014 data[i], data[j] = data[j], data[i]
1015 i++
1016 j--
1017 }
1018 }
1019
1020 func swapRangeCmpFunc[E any](data []E, a, b, n int, cmp func(a, b E) int) {
1021 for i := 0; i < n; i++ {
1022 data[a+i], data[b+i] = data[b+i], data[a+i]
1023 }
1024 }
1025
1026 func stableCmpFunc[E any](data []E, n int, cmp func(a, b E) int) {
1027 blockSize := 20 // must be > 0
1028 a, b := 0, blockSize
1029 for b <= n {
1030 insertionSortCmpFunc(data, a, b, cmp)
1031 a = b
1032 b += blockSize
1033 }
1034 insertionSortCmpFunc(data, a, n, cmp)
1035
1036 for blockSize < n {
1037 a, b = 0, 2*blockSize
1038 for b <= n {
1039 symMergeCmpFunc(data, a, a+blockSize, b, cmp)
1040 a = b
1041 b += 2 * blockSize
1042 }
1043 if m := a + blockSize; m < n {
1044 symMergeCmpFunc(data, a, m, n, cmp)
1045 }
1046 blockSize *= 2
1047 }
1048 }
1049
1050 // symMergeCmpFunc merges the two sorted subsequences data[a:m] and data[m:b] using
1051 // the SymMerge algorithm from Pok-Son Kim and Arne Kutzner, "Stable Minimum
1052 // Storage Merging by Symmetric Comparisons", in Susanne Albers and Tomasz
1053 // Radzik, editors, Algorithms - ESA 2004, volume 3221 of Lecture Notes in
1054 // Computer Science, pages 714-723. Springer, 2004.
1055 //
1056 // Let M = m-a and N = b-n. Wolog M < N.
1057 // The recursion depth is bound by ceil(log(N+M)).
1058 // The algorithm needs O(M*log(N/M + 1)) calls to data.Less.
1059 // The algorithm needs O((M+N)*log(M)) calls to data.Swap.
1060 //
1061 // The paper gives O((M+N)*log(M)) as the number of assignments assuming a
1062 // rotation algorithm which uses O(M+N+gcd(M+N)) assignments. The argumentation
1063 // in the paper carries through for Swap operations, especially as the block
1064 // swapping rotate uses only O(M+N) Swaps.
1065 //
1066 // symMerge assumes non-degenerate arguments: a < m && m < b.
1067 // Having the caller check this condition eliminates many leaf recursion calls,
1068 // which improves performance.
1069 func symMergeCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) {
1070 // Avoid unnecessary recursions of symMerge
1071 // by direct insertion of data[a] into data[m:b]
1072 // if data[a:m] only contains one element.
1073 if m-a == 1 {
1074 // Use binary search to find the lowest index i
1075 // such that data[i] >= data[a] for m <= i < b.
1076 // Exit the search loop with i == b in case no such index exists.
1077 i := m
1078 j := b
1079 for i < j {
1080 h := int(uint(i+j) >> 1)
1081 if cmp(data[h], data[a]) < 0 {
1082 i = h + 1
1083 } else {
1084 j = h
1085 }
1086 }
1087 // Swap values until data[a] reaches the position before i.
1088 for k := a; k < i-1; k++ {
1089 data[k], data[k+1] = data[k+1], data[k]
1090 }
1091 return
1092 }
1093
1094 // Avoid unnecessary recursions of symMerge
1095 // by direct insertion of data[m] into data[a:m]
1096 // if data[m:b] only contains one element.
1097 if b-m == 1 {
1098 // Use binary search to find the lowest index i
1099 // such that data[i] > data[m] for a <= i < m.
1100 // Exit the search loop with i == m in case no such index exists.
1101 i := a
1102 j := m
1103 for i < j {
1104 h := int(uint(i+j) >> 1)
1105 if !(cmp(data[m], data[h]) < 0) {
1106 i = h + 1
1107 } else {
1108 j = h
1109 }
1110 }
1111 // Swap values until data[m] reaches the position i.
1112 for k := m; k > i; k-- {
1113 data[k], data[k-1] = data[k-1], data[k]
1114 }
1115 return
1116 }
1117
1118 mid := int(uint(a+b) >> 1)
1119 n := mid + m
1120 var start, r int
1121 if m > mid {
1122 start = n - b
1123 r = mid
1124 } else {
1125 start = a
1126 r = m
1127 }
1128 p := n - 1
1129
1130 for start < r {
1131 c := int(uint(start+r) >> 1)
1132 if !(cmp(data[p-c], data[c]) < 0) {
1133 start = c + 1
1134 } else {
1135 r = c
1136 }
1137 }
1138
1139 end := n - start
1140 if start < m && m < end {
1141 rotateCmpFunc(data, start, m, end, cmp)
1142 }
1143 if a < start && start < mid {
1144 symMergeCmpFunc(data, a, start, mid, cmp)
1145 }
1146 if mid < end && end < b {
1147 symMergeCmpFunc(data, mid, end, b, cmp)
1148 }
1149 }
1150
1151 // rotateCmpFunc rotates two consecutive blocks u = data[a:m] and v = data[m:b] in data:
1152 // Data of the form 'x u v y' is changed to 'x v u y'.
1153 // rotate performs at most b-a many calls to data.Swap,
1154 // and it assumes non-degenerate arguments: a < m && m < b.
1155 func rotateCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) {
1156 i := m - a
1157 j := b - m
1158
1159 for i != j {
1160 if i > j {
1161 swapRangeCmpFunc(data, m-i, m, j, cmp)
1162 i -= j
1163 } else {
1164 swapRangeCmpFunc(data, m-i, m+j-i, i, cmp)
1165 j -= i
1166 }
1167 }
1168 // i == j
1169 swapRangeCmpFunc(data, m-i, m, i, cmp)
1170 }
1171 // Code generated by gen_sort_variants.go; DO NOT EDIT.
1172
1173 // Copyright 2022 The Go Authors. All rights reserved.
1174 // Use of this source code is governed by a BSD-style
1175 // license that can be found in the LICENSE file.
1176
1177 // package slices
1178
1179 // import "cmp"
1180
1181 // insertionSortOrdered sorts data[a:b] using insertion sort.
1182 func insertionSortOrdered[E cmp.Ordered](data []E, a, b int) {
1183 for i := a + 1; i < b; i++ {
1184 for j := i; j > a && cmp.Less(data[j], data[j-1]); j-- {
1185 data[j], data[j-1] = data[j-1], data[j]
1186 }
1187 }
1188 }
1189
1190 // siftDownOrdered implements the heap property on data[lo:hi].
1191 // first is an offset into the array where the root of the heap lies.
1192 func siftDownOrdered[E cmp.Ordered](data []E, lo, hi, first int) {
1193 root := lo
1194 for {
1195 child := 2*root + 1
1196 if child >= hi {
1197 break
1198 }
1199 if child+1 < hi && cmp.Less(data[first+child], data[first+child+1]) {
1200 child++
1201 }
1202 if !cmp.Less(data[first+root], data[first+child]) {
1203 return
1204 }
1205 data[first+root], data[first+child] = data[first+child], data[first+root]
1206 root = child
1207 }
1208 }
1209
1210 func heapSortOrdered[E cmp.Ordered](data []E, a, b int) {
1211 first := a
1212 lo := 0
1213 hi := b - a
1214
1215 // Build heap with greatest element at top.
1216 for i := (hi - 1) / 2; i >= 0; i-- {
1217 siftDownOrdered(data, i, hi, first)
1218 }
1219
1220 // Pop elements, largest first, into end of data.
1221 for i := hi - 1; i >= 0; i-- {
1222 data[first], data[first+i] = data[first+i], data[first]
1223 siftDownOrdered(data, lo, i, first)
1224 }
1225 }
1226
1227 // pdqsortOrdered sorts data[a:b].
1228 // The algorithm based on pattern-defeating quicksort(pdqsort), but without the optimizations from BlockQuicksort.
1229 // pdqsort paper: https://arxiv.org/pdf/2106.05123.pdf
1230 // C++ implementation: https://github.com/orlp/pdqsort
1231 // Rust implementation: https://docs.rs/pdqsort/latest/pdqsort/
1232 // limit is the number of allowed bad (very unbalanced) pivots before falling back to heapsort.
1233 func pdqsortOrdered[E cmp.Ordered](data []E, a, b, limit int) {
1234 const maxInsertion = 12
1235
1236 var (
1237 wasBalanced = true // whether the last partitioning was reasonably balanced
1238 wasPartitioned = true // whether the slice was already partitioned
1239 )
1240
1241 for {
1242 length := b - a
1243
1244 if length <= maxInsertion {
1245 insertionSortOrdered(data, a, b)
1246 return
1247 }
1248
1249 // Fall back to heapsort if too many bad choices were made.
1250 if limit == 0 {
1251 heapSortOrdered(data, a, b)
1252 return
1253 }
1254
1255 // If the last partitioning was imbalanced, we need to breaking patterns.
1256 if !wasBalanced {
1257 breakPatternsOrdered(data, a, b)
1258 limit--
1259 }
1260
1261 pivot, hint := choosePivotOrdered(data, a, b)
1262 if hint == decreasingHint {
1263 reverseRangeOrdered(data, a, b)
1264 // The chosen pivot was pivot-a elements after the start of the array.
1265 // After reversing it is pivot-a elements before the end of the array.
1266 // The idea came from Rust's implementation.
1267 pivot = (b - 1) - (pivot - a)
1268 hint = increasingHint
1269 }
1270
1271 // The slice is likely already sorted.
1272 if wasBalanced && wasPartitioned && hint == increasingHint {
1273 if partialInsertionSortOrdered(data, a, b) {
1274 return
1275 }
1276 }
1277
1278 // Probably the slice contains many duplicate elements, partition the slice into
1279 // elements equal to and elements greater than the pivot.
1280 if a > 0 && !cmp.Less(data[a-1], data[pivot]) {
1281 mid := partitionEqualOrdered(data, a, b, pivot)
1282 a = mid
1283 continue
1284 }
1285
1286 mid, alreadyPartitioned := partitionOrdered(data, a, b, pivot)
1287 wasPartitioned = alreadyPartitioned
1288
1289 leftLen, rightLen := mid-a, b-mid
1290 balanceThreshold := length / 8
1291 if leftLen < rightLen {
1292 wasBalanced = leftLen >= balanceThreshold
1293 pdqsortOrdered(data, a, mid, limit)
1294 a = mid + 1
1295 } else {
1296 wasBalanced = rightLen >= balanceThreshold
1297 pdqsortOrdered(data, mid+1, b, limit)
1298 b = mid
1299 }
1300 }
1301 }
1302
1303 // partitionOrdered does one quicksort partition.
1304 // Let p = data[pivot]
1305 // Moves elements in data[a:b] around, so that data[i]<p and data[j]>=p for i<newpivot and j>newpivot.
1306 // On return, data[newpivot] = p
1307 func partitionOrdered[E cmp.Ordered](data []E, a, b, pivot int) (newpivot int, alreadyPartitioned bool) {
1308 data[a], data[pivot] = data[pivot], data[a]
1309 i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned
1310
1311 for i <= j && cmp.Less(data[i], data[a]) {
1312 i++
1313 }
1314 for i <= j && !cmp.Less(data[j], data[a]) {
1315 j--
1316 }
1317 if i > j {
1318 data[j], data[a] = data[a], data[j]
1319 return j, true
1320 }
1321 data[i], data[j] = data[j], data[i]
1322 i++
1323 j--
1324
1325 for {
1326 for i <= j && cmp.Less(data[i], data[a]) {
1327 i++
1328 }
1329 for i <= j && !cmp.Less(data[j], data[a]) {
1330 j--
1331 }
1332 if i > j {
1333 break
1334 }
1335 data[i], data[j] = data[j], data[i]
1336 i++
1337 j--
1338 }
1339 data[j], data[a] = data[a], data[j]
1340 return j, false
1341 }
1342
1343 // partitionEqualOrdered partitions data[a:b] into elements equal to data[pivot] followed by elements greater than data[pivot].
1344 // It assumed that data[a:b] does not contain elements smaller than the data[pivot].
1345 func partitionEqualOrdered[E cmp.Ordered](data []E, a, b, pivot int) (newpivot int) {
1346 data[a], data[pivot] = data[pivot], data[a]
1347 i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned
1348
1349 for {
1350 for i <= j && !cmp.Less(data[a], data[i]) {
1351 i++
1352 }
1353 for i <= j && cmp.Less(data[a], data[j]) {
1354 j--
1355 }
1356 if i > j {
1357 break
1358 }
1359 data[i], data[j] = data[j], data[i]
1360 i++
1361 j--
1362 }
1363 return i
1364 }
1365
1366 // partialInsertionSortOrdered partially sorts a slice, returns true if the slice is sorted at the end.
1367 func partialInsertionSortOrdered[E cmp.Ordered](data []E, a, b int) bool {
1368 const (
1369 maxSteps = 5 // maximum number of adjacent out-of-order pairs that will get shifted
1370 shortestShifting = 50 // don't shift any elements on short arrays
1371 )
1372 i := a + 1
1373 for j := 0; j < maxSteps; j++ {
1374 for i < b && !cmp.Less(data[i], data[i-1]) {
1375 i++
1376 }
1377
1378 if i == b {
1379 return true
1380 }
1381
1382 if b-a < shortestShifting {
1383 return false
1384 }
1385
1386 data[i], data[i-1] = data[i-1], data[i]
1387
1388 // Shift the smaller one to the left.
1389 if i-a >= 2 {
1390 for j := i - 1; j >= 1; j-- {
1391 if !cmp.Less(data[j], data[j-1]) {
1392 break
1393 }
1394 data[j], data[j-1] = data[j-1], data[j]
1395 }
1396 }
1397 // Shift the greater one to the right.
1398 if b-i >= 2 {
1399 for j := i + 1; j < b; j++ {
1400 if !cmp.Less(data[j], data[j-1]) {
1401 break
1402 }
1403 data[j], data[j-1] = data[j-1], data[j]
1404 }
1405 }
1406 }
1407 return false
1408 }
1409
1410 // breakPatternsOrdered scatters some elements around in an attempt to break some patterns
1411 // that might cause imbalanced partitions in quicksort.
1412 func breakPatternsOrdered[E cmp.Ordered](data []E, a, b int) {
1413 length := b - a
1414 if length >= 8 {
1415 random := xorshift(length)
1416 modulus := nextPowerOfTwo(length)
1417
1418 for idx := a + (length/4)*2 - 1; idx <= a+(length/4)*2+1; idx++ {
1419 other := int(uint(random.Next()) & (modulus - 1))
1420 if other >= length {
1421 other -= length
1422 }
1423 data[idx], data[a+other] = data[a+other], data[idx]
1424 }
1425 }
1426 }
1427
1428 // choosePivotOrdered chooses a pivot in data[a:b].
1429 //
1430 // [0,8): chooses a static pivot.
1431 // [8,shortestNinther): uses the simple median-of-three method.
1432 // [shortestNinther,∞): uses the Tukey ninther method.
1433 func choosePivotOrdered[E cmp.Ordered](data []E, a, b int) (pivot int, hint sortedHint) {
1434 const (
1435 shortestNinther = 50
1436 maxSwaps = 4 * 3
1437 )
1438
1439 l := b - a
1440
1441 var (
1442 swaps int
1443 i = a + l/4*1
1444 j = a + l/4*2
1445 k = a + l/4*3
1446 )
1447
1448 if l >= 8 {
1449 if l >= shortestNinther {
1450 // Tukey ninther method, the idea came from Rust's implementation.
1451 i = medianAdjacentOrdered(data, i, &swaps)
1452 j = medianAdjacentOrdered(data, j, &swaps)
1453 k = medianAdjacentOrdered(data, k, &swaps)
1454 }
1455 // Find the median among i, j, k and stores it into j.
1456 j = medianOrdered(data, i, j, k, &swaps)
1457 }
1458
1459 switch swaps {
1460 case 0:
1461 return j, increasingHint
1462 case maxSwaps:
1463 return j, decreasingHint
1464 default:
1465 return j, unknownHint
1466 }
1467 }
1468
1469 // order2Ordered returns x,y where data[x] <= data[y], where x,y=a,b or x,y=b,a.
1470 func order2Ordered[E cmp.Ordered](data []E, a, b int, swaps *int) (int, int) {
1471 if cmp.Less(data[b], data[a]) {
1472 *swaps++
1473 return b, a
1474 }
1475 return a, b
1476 }
1477
1478 // medianOrdered returns x where data[x] is the median of data[a],data[b],data[c], where x is a, b, or c.
1479 func medianOrdered[E cmp.Ordered](data []E, a, b, c int, swaps *int) int {
1480 a, b = order2Ordered(data, a, b, swaps)
1481 b, c = order2Ordered(data, b, c, swaps)
1482 a, b = order2Ordered(data, a, b, swaps)
1483 return b
1484 }
1485
1486 // medianAdjacentOrdered finds the median of data[a - 1], data[a], data[a + 1] and stores the index into a.
1487 func medianAdjacentOrdered[E cmp.Ordered](data []E, a int, swaps *int) int {
1488 return medianOrdered(data, a-1, a, a+1, swaps)
1489 }
1490
1491 func reverseRangeOrdered[E cmp.Ordered](data []E, a, b int) {
1492 i := a
1493 j := b - 1
1494 for i < j {
1495 data[i], data[j] = data[j], data[i]
1496 i++
1497 j--
1498 }
1499 }
1500
1501 func swapRangeOrdered[E cmp.Ordered](data []E, a, b, n int) {
1502 for i := 0; i < n; i++ {
1503 data[a+i], data[b+i] = data[b+i], data[a+i]
1504 }
1505 }
1506
1507 func stableOrdered[E cmp.Ordered](data []E, n int) {
1508 blockSize := 20 // must be > 0
1509 a, b := 0, blockSize
1510 for b <= n {
1511 insertionSortOrdered(data, a, b)
1512 a = b
1513 b += blockSize
1514 }
1515 insertionSortOrdered(data, a, n)
1516
1517 for blockSize < n {
1518 a, b = 0, 2*blockSize
1519 for b <= n {
1520 symMergeOrdered(data, a, a+blockSize, b)
1521 a = b
1522 b += 2 * blockSize
1523 }
1524 if m := a + blockSize; m < n {
1525 symMergeOrdered(data, a, m, n)
1526 }
1527 blockSize *= 2
1528 }
1529 }
1530
1531 // symMergeOrdered merges the two sorted subsequences data[a:m] and data[m:b] using
1532 // the SymMerge algorithm from Pok-Son Kim and Arne Kutzner, "Stable Minimum
1533 // Storage Merging by Symmetric Comparisons", in Susanne Albers and Tomasz
1534 // Radzik, editors, Algorithms - ESA 2004, volume 3221 of Lecture Notes in
1535 // Computer Science, pages 714-723. Springer, 2004.
1536 //
1537 // Let M = m-a and N = b-n. Wolog M < N.
1538 // The recursion depth is bound by ceil(log(N+M)).
1539 // The algorithm needs O(M*log(N/M + 1)) calls to data.Less.
1540 // The algorithm needs O((M+N)*log(M)) calls to data.Swap.
1541 //
1542 // The paper gives O((M+N)*log(M)) as the number of assignments assuming a
1543 // rotation algorithm which uses O(M+N+gcd(M+N)) assignments. The argumentation
1544 // in the paper carries through for Swap operations, especially as the block
1545 // swapping rotate uses only O(M+N) Swaps.
1546 //
1547 // symMerge assumes non-degenerate arguments: a < m && m < b.
1548 // Having the caller check this condition eliminates many leaf recursion calls,
1549 // which improves performance.
1550 func symMergeOrdered[E cmp.Ordered](data []E, a, m, b int) {
1551 // Avoid unnecessary recursions of symMerge
1552 // by direct insertion of data[a] into data[m:b]
1553 // if data[a:m] only contains one element.
1554 if m-a == 1 {
1555 // Use binary search to find the lowest index i
1556 // such that data[i] >= data[a] for m <= i < b.
1557 // Exit the search loop with i == b in case no such index exists.
1558 i := m
1559 j := b
1560 for i < j {
1561 h := int(uint(i+j) >> 1)
1562 if cmp.Less(data[h], data[a]) {
1563 i = h + 1
1564 } else {
1565 j = h
1566 }
1567 }
1568 // Swap values until data[a] reaches the position before i.
1569 for k := a; k < i-1; k++ {
1570 data[k], data[k+1] = data[k+1], data[k]
1571 }
1572 return
1573 }
1574
1575 // Avoid unnecessary recursions of symMerge
1576 // by direct insertion of data[m] into data[a:m]
1577 // if data[m:b] only contains one element.
1578 if b-m == 1 {
1579 // Use binary search to find the lowest index i
1580 // such that data[i] > data[m] for a <= i < m.
1581 // Exit the search loop with i == m in case no such index exists.
1582 i := a
1583 j := m
1584 for i < j {
1585 h := int(uint(i+j) >> 1)
1586 if !cmp.Less(data[m], data[h]) {
1587 i = h + 1
1588 } else {
1589 j = h
1590 }
1591 }
1592 // Swap values until data[m] reaches the position i.
1593 for k := m; k > i; k-- {
1594 data[k], data[k-1] = data[k-1], data[k]
1595 }
1596 return
1597 }
1598
1599 mid := int(uint(a+b) >> 1)
1600 n := mid + m
1601 var start, r int
1602 if m > mid {
1603 start = n - b
1604 r = mid
1605 } else {
1606 start = a
1607 r = m
1608 }
1609 p := n - 1
1610
1611 for start < r {
1612 c := int(uint(start+r) >> 1)
1613 if !cmp.Less(data[p-c], data[c]) {
1614 start = c + 1
1615 } else {
1616 r = c
1617 }
1618 }
1619
1620 end := n - start
1621 if start < m && m < end {
1622 rotateOrdered(data, start, m, end)
1623 }
1624 if a < start && start < mid {
1625 symMergeOrdered(data, a, start, mid)
1626 }
1627 if mid < end && end < b {
1628 symMergeOrdered(data, mid, end, b)
1629 }
1630 }
1631
1632 // rotateOrdered rotates two consecutive blocks u = data[a:m] and v = data[m:b] in data:
1633 // Data of the form 'x u v y' is changed to 'x v u y'.
1634 // rotate performs at most b-a many calls to data.Swap,
1635 // and it assumes non-degenerate arguments: a < m && m < b.
1636 func rotateOrdered[E cmp.Ordered](data []E, a, m, b int) {
1637 i := m - a
1638 j := b - m
1639
1640 for i != j {
1641 if i > j {
1642 swapRangeOrdered(data, m-i, m, j)
1643 i -= j
1644 } else {
1645 swapRangeOrdered(data, m-i, m+j-i, i)
1646 j -= i
1647 }
1648 }
1649 // i == j
1650 swapRangeOrdered(data, m-i, m, i)
1651 }