1 // Code generated by gen_sort_variants.go; DO NOT EDIT.
3 // Copyright 2022 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
9 // insertionSortCmpFunc sorts data[a:b] using insertion sort.
10 func insertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
11 for i := a + 1; i < b; i++ {
12 for j := i; j > a && (cmp(data[j], data[j-1]) < 0); j-- {
13 data[j], data[j-1] = data[j-1], data[j]
18 // siftDownCmpFunc implements the heap property on data[lo:hi].
19 // first is an offset into the array where the root of the heap lies.
20 func siftDownCmpFunc[E any](data []E, lo, hi, first int, cmp func(a, b E) int) {
27 if child+1 < hi && (cmp(data[first+child], data[first+child+1]) < 0) {
30 if !(cmp(data[first+root], data[first+child]) < 0) {
33 data[first+root], data[first+child] = data[first+child], data[first+root]
38 func heapSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
43 // Build heap with greatest element at top.
44 for i := (hi - 1) / 2; i >= 0; i-- {
45 siftDownCmpFunc(data, i, hi, first, cmp)
48 // Pop elements, largest first, into end of data.
49 for i := hi - 1; i >= 0; i-- {
50 data[first], data[first+i] = data[first+i], data[first]
51 siftDownCmpFunc(data, lo, i, first, cmp)
55 // pdqsortCmpFunc sorts data[a:b].
56 // The algorithm based on pattern-defeating quicksort(pdqsort), but without the optimizations from BlockQuicksort.
57 // pdqsort paper: https://arxiv.org/pdf/2106.05123.pdf
58 // C++ implementation: https://github.com/orlp/pdqsort
59 // Rust implementation: https://docs.rs/pdqsort/latest/pdqsort/
60 // limit is the number of allowed bad (very unbalanced) pivots before falling back to heapsort.
61 func pdqsortCmpFunc[E any](data []E, a, b, limit int, cmp func(a, b E) int) {
62 const maxInsertion = 12
65 wasBalanced = true // whether the last partitioning was reasonably balanced
66 wasPartitioned = true // whether the slice was already partitioned
72 if length <= maxInsertion {
73 insertionSortCmpFunc(data, a, b, cmp)
77 // Fall back to heapsort if too many bad choices were made.
79 heapSortCmpFunc(data, a, b, cmp)
83 // If the last partitioning was imbalanced, we need to breaking patterns.
85 breakPatternsCmpFunc(data, a, b, cmp)
89 pivot, hint := choosePivotCmpFunc(data, a, b, cmp)
90 if hint == decreasingHint {
91 reverseRangeCmpFunc(data, a, b, cmp)
92 // The chosen pivot was pivot-a elements after the start of the array.
93 // After reversing it is pivot-a elements before the end of the array.
94 // The idea came from Rust's implementation.
95 pivot = (b - 1) - (pivot - a)
99 // The slice is likely already sorted.
100 if wasBalanced && wasPartitioned && hint == increasingHint {
101 if partialInsertionSortCmpFunc(data, a, b, cmp) {
106 // Probably the slice contains many duplicate elements, partition the slice into
107 // elements equal to and elements greater than the pivot.
108 if a > 0 && !(cmp(data[a-1], data[pivot]) < 0) {
109 mid := partitionEqualCmpFunc(data, a, b, pivot, cmp)
114 mid, alreadyPartitioned := partitionCmpFunc(data, a, b, pivot, cmp)
115 wasPartitioned = alreadyPartitioned
117 leftLen, rightLen := mid-a, b-mid
118 balanceThreshold := length / 8
119 if leftLen < rightLen {
120 wasBalanced = leftLen >= balanceThreshold
121 pdqsortCmpFunc(data, a, mid, limit, cmp)
124 wasBalanced = rightLen >= balanceThreshold
125 pdqsortCmpFunc(data, mid+1, b, limit, cmp)
131 // partitionCmpFunc does one quicksort partition.
132 // Let p = data[pivot]
133 // Moves elements in data[a:b] around, so that data[i]<p and data[j]>=p for i<newpivot and j>newpivot.
134 // On return, data[newpivot] = p
135 func partitionCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (newpivot int, alreadyPartitioned bool) {
136 data[a], data[pivot] = data[pivot], data[a]
137 i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned
139 for i <= j && (cmp(data[i], data[a]) < 0) {
142 for i <= j && !(cmp(data[j], data[a]) < 0) {
146 data[j], data[a] = data[a], data[j]
149 data[i], data[j] = data[j], data[i]
154 for i <= j && (cmp(data[i], data[a]) < 0) {
157 for i <= j && !(cmp(data[j], data[a]) < 0) {
163 data[i], data[j] = data[j], data[i]
167 data[j], data[a] = data[a], data[j]
171 // partitionEqualCmpFunc partitions data[a:b] into elements equal to data[pivot] followed by elements greater than data[pivot].
172 // It assumed that data[a:b] does not contain elements smaller than the data[pivot].
173 func partitionEqualCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (newpivot int) {
174 data[a], data[pivot] = data[pivot], data[a]
175 i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned
178 for i <= j && !(cmp(data[a], data[i]) < 0) {
181 for i <= j && (cmp(data[a], data[j]) < 0) {
187 data[i], data[j] = data[j], data[i]
194 // partialInsertionSortCmpFunc partially sorts a slice, returns true if the slice is sorted at the end.
195 func partialInsertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) bool {
197 maxSteps = 5 // maximum number of adjacent out-of-order pairs that will get shifted
198 shortestShifting = 50 // don't shift any elements on short arrays
201 for j := 0; j < maxSteps; j++ {
202 for i < b && !(cmp(data[i], data[i-1]) < 0) {
210 if b-a < shortestShifting {
214 data[i], data[i-1] = data[i-1], data[i]
216 // Shift the smaller one to the left.
218 for j := i - 1; j >= 1; j-- {
219 if !(cmp(data[j], data[j-1]) < 0) {
222 data[j], data[j-1] = data[j-1], data[j]
225 // Shift the greater one to the right.
227 for j := i + 1; j < b; j++ {
228 if !(cmp(data[j], data[j-1]) < 0) {
231 data[j], data[j-1] = data[j-1], data[j]
238 // breakPatternsCmpFunc scatters some elements around in an attempt to break some patterns
239 // that might cause imbalanced partitions in quicksort.
240 func breakPatternsCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
243 random := xorshift(length)
244 modulus := nextPowerOfTwo(length)
246 for idx := a + (length/4)*2 - 1; idx <= a+(length/4)*2+1; idx++ {
247 other := int(uint(random.Next()) & (modulus - 1))
251 data[idx], data[a+other] = data[a+other], data[idx]
256 // choosePivotCmpFunc chooses a pivot in data[a:b].
258 // [0,8): chooses a static pivot.
259 // [8,shortestNinther): uses the simple median-of-three method.
260 // [shortestNinther,∞): uses the Tukey ninther method.
261 func choosePivotCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) (pivot int, hint sortedHint) {
277 if l >= shortestNinther {
278 // Tukey ninther method, the idea came from Rust's implementation.
279 i = medianAdjacentCmpFunc(data, i, &swaps, cmp)
280 j = medianAdjacentCmpFunc(data, j, &swaps, cmp)
281 k = medianAdjacentCmpFunc(data, k, &swaps, cmp)
283 // Find the median among i, j, k and stores it into j.
284 j = medianCmpFunc(data, i, j, k, &swaps, cmp)
289 return j, increasingHint
291 return j, decreasingHint
293 return j, unknownHint
297 // order2CmpFunc returns x,y where data[x] <= data[y], where x,y=a,b or x,y=b,a.
298 func order2CmpFunc[E any](data []E, a, b int, swaps *int, cmp func(a, b E) int) (int, int) {
299 if cmp(data[b], data[a]) < 0 {
306 // medianCmpFunc returns x where data[x] is the median of data[a],data[b],data[c], where x is a, b, or c.
307 func medianCmpFunc[E any](data []E, a, b, c int, swaps *int, cmp func(a, b E) int) int {
308 a, b = order2CmpFunc(data, a, b, swaps, cmp)
309 b, c = order2CmpFunc(data, b, c, swaps, cmp)
310 a, b = order2CmpFunc(data, a, b, swaps, cmp)
314 // medianAdjacentCmpFunc finds the median of data[a - 1], data[a], data[a + 1] and stores the index into a.
315 func medianAdjacentCmpFunc[E any](data []E, a int, swaps *int, cmp func(a, b E) int) int {
316 return medianCmpFunc(data, a-1, a, a+1, swaps, cmp)
319 func reverseRangeCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
323 data[i], data[j] = data[j], data[i]
329 func swapRangeCmpFunc[E any](data []E, a, b, n int, cmp func(a, b E) int) {
330 for i := 0; i < n; i++ {
331 data[a+i], data[b+i] = data[b+i], data[a+i]
335 func stableCmpFunc[E any](data []E, n int, cmp func(a, b E) int) {
336 blockSize := 20 // must be > 0
339 insertionSortCmpFunc(data, a, b, cmp)
343 insertionSortCmpFunc(data, a, n, cmp)
346 a, b = 0, 2*blockSize
348 symMergeCmpFunc(data, a, a+blockSize, b, cmp)
352 if m := a + blockSize; m < n {
353 symMergeCmpFunc(data, a, m, n, cmp)
359 // symMergeCmpFunc merges the two sorted subsequences data[a:m] and data[m:b] using
360 // the SymMerge algorithm from Pok-Son Kim and Arne Kutzner, "Stable Minimum
361 // Storage Merging by Symmetric Comparisons", in Susanne Albers and Tomasz
362 // Radzik, editors, Algorithms - ESA 2004, volume 3221 of Lecture Notes in
363 // Computer Science, pages 714-723. Springer, 2004.
365 // Let M = m-a and N = b-n. Wolog M < N.
366 // The recursion depth is bound by ceil(log(N+M)).
367 // The algorithm needs O(M*log(N/M + 1)) calls to data.Less.
368 // The algorithm needs O((M+N)*log(M)) calls to data.Swap.
370 // The paper gives O((M+N)*log(M)) as the number of assignments assuming a
371 // rotation algorithm which uses O(M+N+gcd(M+N)) assignments. The argumentation
372 // in the paper carries through for Swap operations, especially as the block
373 // swapping rotate uses only O(M+N) Swaps.
375 // symMerge assumes non-degenerate arguments: a < m && m < b.
376 // Having the caller check this condition eliminates many leaf recursion calls,
377 // which improves performance.
378 func symMergeCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) {
379 // Avoid unnecessary recursions of symMerge
380 // by direct insertion of data[a] into data[m:b]
381 // if data[a:m] only contains one element.
383 // Use binary search to find the lowest index i
384 // such that data[i] >= data[a] for m <= i < b.
385 // Exit the search loop with i == b in case no such index exists.
389 h := int(uint(i+j) >> 1)
390 if cmp(data[h], data[a]) < 0 {
396 // Swap values until data[a] reaches the position before i.
397 for k := a; k < i-1; k++ {
398 data[k], data[k+1] = data[k+1], data[k]
403 // Avoid unnecessary recursions of symMerge
404 // by direct insertion of data[m] into data[a:m]
405 // if data[m:b] only contains one element.
407 // Use binary search to find the lowest index i
408 // such that data[i] > data[m] for a <= i < m.
409 // Exit the search loop with i == m in case no such index exists.
413 h := int(uint(i+j) >> 1)
414 if !(cmp(data[m], data[h]) < 0) {
420 // Swap values until data[m] reaches the position i.
421 for k := m; k > i; k-- {
422 data[k], data[k-1] = data[k-1], data[k]
427 mid := int(uint(a+b) >> 1)
440 c := int(uint(start+r) >> 1)
441 if !(cmp(data[p-c], data[c]) < 0) {
449 if start < m && m < end {
450 rotateCmpFunc(data, start, m, end, cmp)
452 if a < start && start < mid {
453 symMergeCmpFunc(data, a, start, mid, cmp)
455 if mid < end && end < b {
456 symMergeCmpFunc(data, mid, end, b, cmp)
460 // rotateCmpFunc rotates two consecutive blocks u = data[a:m] and v = data[m:b] in data:
461 // Data of the form 'x u v y' is changed to 'x v u y'.
462 // rotate performs at most b-a many calls to data.Swap,
463 // and it assumes non-degenerate arguments: a < m && m < b.
464 func rotateCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) {
470 swapRangeCmpFunc(data, m-i, m, j, cmp)
473 swapRangeCmpFunc(data, m-i, m+j-i, i, cmp)
478 swapRangeCmpFunc(data, m-i, m, i, cmp)