// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:generate go run genzfunc.go

// Package sort provides primitives for sorting slices and user-defined collections.
package sort // An implementation of Interface can be sorted by the routines in this package. // The methods refer to elements of the underlying collection by integer index. type Interface interface { // Len is the number of elements in the collection. Len() int // Less reports whether the element with index i // must sort before the element with index j. // // If both Less(i, j) and Less(j, i) are false, // then the elements at index i and j are considered equal. // Sort may place equal elements in any order in the final result, // while Stable preserves the original input order of equal elements. // // Less must describe a transitive ordering: // - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well. // - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well. // // Note that floating-point comparison (the < operator on float32 or float64 values) // is not a transitive ordering when not-a-number (NaN) values are involved. // See Float64Slice.Less for a correct implementation for floating-point values. Less(i, j int) bool // Swap swaps the elements with indexes i and j. Swap(i, j int) } // insertionSort sorts data[a:b] using insertion sort. func insertionSort( Interface, , int) { for := + 1; < ; ++ { for := ; > && .Less(, -1); -- { .Swap(, -1) } } } // siftDown implements the heap property on data[lo:hi]. // first is an offset into the array where the root of the heap lies. func siftDown( Interface, , , int) { := for { := 2* + 1 if >= { break } if +1 < && .Less(+, ++1) { ++ } if !.Less(+, +) { return } .Swap(+, +) = } } func heapSort( Interface, , int) { := := 0 := - // Build heap with greatest element at top. for := ( - 1) / 2; >= 0; -- { siftDown(, , , ) } // Pop elements, largest first, into end of data. for := - 1; >= 0; -- { .Swap(, +) siftDown(, , , ) } } // Quicksort, loosely following Bentley and McIlroy, // ``Engineering a Sort Function,'' SP&E November 1993. // medianOfThree moves the median of the three values data[m0], data[m1], data[m2] into data[m1]. func medianOfThree( Interface, , , int) { // sort 3 elements if .Less(, ) { .Swap(, ) } // data[m0] <= data[m1] if .Less(, ) { .Swap(, ) // data[m0] <= data[m2] && data[m1] < data[m2] if .Less(, ) { .Swap(, ) } } // now data[m0] <= data[m1] <= data[m2] } func swapRange( Interface, , , int) { for := 0; < ; ++ { .Swap(+, +) } } func doPivot( Interface, , int) (, int) { := int(uint(+) >> 1) // Written like this to avoid integer overflow. if - > 40 { // Tukey's ``Ninther,'' median of three medians of three. := ( - ) / 8 medianOfThree(, , +, +2*) medianOfThree(, , -, +) medianOfThree(, -1, -1-, -1-2*) } medianOfThree(, , , -1) // Invariants are: // data[lo] = pivot (set up by ChoosePivot) // data[lo < i < a] < pivot // data[a <= i < b] <= pivot // data[b <= i < c] unexamined // data[c <= i < hi-1] > pivot // data[hi-1] >= pivot := , := +1, -1 for ; < && .Less(, ); ++ { } := for { for ; < && !.Less(, ); ++ { // data[b] <= pivot } for ; < && .Less(, -1); -- { // data[c-1] > pivot } if >= { break } // data[b] > pivot; data[c-1] <= pivot .Swap(, -1) ++ -- } // If hi-c<3 then there are duplicates (by property of median of nine). // Let's be a bit more conservative, and set border to 5. := - < 5 if ! && - < (-)/4 { // Lets test some points for equality to pivot := 0 if !.Less(, -1) { // data[hi-1] = pivot .Swap(, -1) ++ ++ } if !.Less(-1, ) { // data[b-1] = pivot -- ++ } // m-lo = (hi-lo)/2 > 6 // b-lo > (hi-lo)*3/4-1 > 8 // ==> m < b ==> data[m] <= pivot if !.Less(, ) { // data[m] = pivot .Swap(, -1) -- ++ } // if at least 2 points are equal to pivot, assume skewed distribution = > 1 } if { // Protect against a lot of duplicates // Add invariant: // data[a <= i < b] unexamined // data[b <= i < c] = pivot for { for ; < && !.Less(-1, ); -- { // data[b] == pivot } for ; < && .Less(, ); ++ { // data[a] < pivot } if >= { break } // data[a] == pivot; data[b-1] < pivot .Swap(, -1) ++ -- } } // Swap pivot into middle .Swap(, -1) return - 1, } func quickSort( Interface, , , int) { for - > 12 { // Use ShellSort for slices <= 12 elements if == 0 { heapSort(, , ) return } -- , := doPivot(, , ) // Avoiding recursion on the larger subproblem guarantees // a stack depth of at most lg(b-a). if - < - { (, , , ) = // i.e., quickSort(data, mhi, b) } else { (, , , ) = // i.e., quickSort(data, a, mlo) } } if - > 1 { // Do ShellSort pass with gap 6 // It could be written in this simplified form cause b-a <= 12 for := + 6; < ; ++ { if .Less(, -6) { .Swap(, -6) } } insertionSort(, , ) } } // Sort sorts data. // It makes one call to data.Len to determine n and O(n*log(n)) calls to // data.Less and data.Swap. The sort is not guaranteed to be stable. func ( Interface) { := .Len() quickSort(, 0, , maxDepth()) } // maxDepth returns a threshold at which quicksort should switch // to heapsort. It returns 2*ceil(lg(n+1)). func maxDepth( int) int { var int for := ; > 0; >>= 1 { ++ } return * 2 } // lessSwap is a pair of Less and Swap function for use with the // auto-generated func-optimized variant of sort.go in // zfuncversion.go. type lessSwap struct { Less func(i, j int) bool Swap func(i, j int) } type reverse struct { // This embedded Interface permits Reverse to use the methods of // another Interface implementation. Interface } // Less returns the opposite of the embedded implementation's Less method. func ( reverse) (, int) bool { return .Interface.Less(, ) } // Reverse returns the reverse order for data. func ( Interface) Interface { return &reverse{} } // IsSorted reports whether data is sorted. func ( Interface) bool { := .Len() for := - 1; > 0; -- { if .Less(, -1) { return false } } return true } // Convenience types for common cases // IntSlice attaches the methods of Interface to []int, sorting in increasing order. type IntSlice []int func ( IntSlice) () int { return len() } func ( IntSlice) (, int) bool { return [] < [] } func ( IntSlice) (, int) { [], [] = [], [] } // Sort is a convenience method: x.Sort() calls Sort(x). func ( IntSlice) () { Sort() } // Float64Slice implements Interface for a []float64, sorting in increasing order, // with not-a-number (NaN) values ordered before other values. type Float64Slice []float64 func ( Float64Slice) () int { return len() } // Less reports whether x[i] should be ordered before x[j], as required by the sort Interface. // Note that floating-point comparison by itself is not a transitive relation: it does not // report a consistent ordering for not-a-number (NaN) values. // This implementation of Less places NaN values before any others, by using: // // x[i] < x[j] || (math.IsNaN(x[i]) && !math.IsNaN(x[j])) // func ( Float64Slice) (, int) bool { return [] < [] || (isNaN([]) && !isNaN([])) } func ( Float64Slice) (, int) { [], [] = [], [] } // isNaN is a copy of math.IsNaN to avoid a dependency on the math package. func isNaN( float64) bool { return != } // Sort is a convenience method: x.Sort() calls Sort(x). func ( Float64Slice) () { Sort() } // StringSlice attaches the methods of Interface to []string, sorting in increasing order. type StringSlice []string func ( StringSlice) () int { return len() } func ( StringSlice) (, int) bool { return [] < [] } func ( StringSlice) (, int) { [], [] = [], [] } // Sort is a convenience method: x.Sort() calls Sort(x). func ( StringSlice) () { Sort() } // Convenience wrappers for common cases // Ints sorts a slice of ints in increasing order. func ( []int) { Sort(IntSlice()) } // Float64s sorts a slice of float64s in increasing order. // Not-a-number (NaN) values are ordered before other values. func ( []float64) { Sort(Float64Slice()) } // Strings sorts a slice of strings in increasing order. func ( []string) { Sort(StringSlice()) } // IntsAreSorted reports whether the slice x is sorted in increasing order. func ( []int) bool { return IsSorted(IntSlice()) } // Float64sAreSorted reports whether the slice x is sorted in increasing order, // with not-a-number (NaN) values before any other values. func ( []float64) bool { return IsSorted(Float64Slice()) } // StringsAreSorted reports whether the slice x is sorted in increasing order. func ( []string) bool { return IsSorted(StringSlice()) } // Notes on stable sorting: // The used algorithms are simple and provable correct on all input and use // only logarithmic additional stack space. They perform well if compared // experimentally to other stable in-place sorting algorithms. // // Remarks on other algorithms evaluated: // - GCC's 4.6.3 stable_sort with merge_without_buffer from libstdc++: // Not faster. // - GCC's __rotate for block rotations: Not faster. // - "Practical in-place mergesort" from Jyrki Katajainen, Tomi A. Pasanen // and Jukka Teuhola; Nordic Journal of Computing 3,1 (1996), 27-40: // The given algorithms are in-place, number of Swap and Assignments // grow as n log n but the algorithm is not stable. // - "Fast Stable In-Place Sorting with O(n) Data Moves" J.I. Munro and // V. Raman in Algorithmica (1996) 16, 115-160: // This algorithm either needs additional 2n bits or works only if there // are enough different elements available to encode some permutations // which have to be undone later (so not stable on any input). // - All the optimal in-place sorting/merging algorithms I found are either // unstable or rely on enough different elements in each step to encode the // performed block rearrangements. See also "In-Place Merging Algorithms", // Denham Coates-Evely, Department of Computer Science, Kings College, // January 2004 and the references in there. // - Often "optimal" algorithms are optimal in the number of assignments // but Interface has only Swap as operation. // Stable sorts data while keeping the original order of equal elements. // // It makes one call to data.Len to determine n, O(n*log(n)) calls to // data.Less and O(n*log(n)*log(n)) calls to data.Swap. func ( Interface) { stable(, .Len()) } func stable( Interface, int) { := 20 // must be > 0 , := 0, for <= { insertionSort(, , ) = += } insertionSort(, , ) for < { , = 0, 2* for <= { symMerge(, , +, ) = += 2 * } if := + ; < { symMerge(, , , ) } *= 2 } } // symMerge merges the two sorted subsequences data[a:m] and data[m:b] using // the SymMerge algorithm from Pok-Son Kim and Arne Kutzner, "Stable Minimum // Storage Merging by Symmetric Comparisons", in Susanne Albers and Tomasz // Radzik, editors, Algorithms - ESA 2004, volume 3221 of Lecture Notes in // Computer Science, pages 714-723. Springer, 2004. // // Let M = m-a and N = b-n. Wolog M < N. // The recursion depth is bound by ceil(log(N+M)). // The algorithm needs O(M*log(N/M + 1)) calls to data.Less. // The algorithm needs O((M+N)*log(M)) calls to data.Swap. // // The paper gives O((M+N)*log(M)) as the number of assignments assuming a // rotation algorithm which uses O(M+N+gcd(M+N)) assignments. The argumentation // in the paper carries through for Swap operations, especially as the block // swapping rotate uses only O(M+N) Swaps. // // symMerge assumes non-degenerate arguments: a < m && m < b. // Having the caller check this condition eliminates many leaf recursion calls, // which improves performance. func symMerge( Interface, , , int) { // Avoid unnecessary recursions of symMerge // by direct insertion of data[a] into data[m:b] // if data[a:m] only contains one element. if - == 1 { // Use binary search to find the lowest index i // such that data[i] >= data[a] for m <= i < b. // Exit the search loop with i == b in case no such index exists. := := for < { := int(uint(+) >> 1) if .Less(, ) { = + 1 } else { = } } // Swap values until data[a] reaches the position before i. for := ; < -1; ++ { .Swap(, +1) } return } // Avoid unnecessary recursions of symMerge // by direct insertion of data[m] into data[a:m] // if data[m:b] only contains one element. if - == 1 { // Use binary search to find the lowest index i // such that data[i] > data[m] for a <= i < m. // Exit the search loop with i == m in case no such index exists. := := for < { := int(uint(+) >> 1) if !.Less(, ) { = + 1 } else { = } } // Swap values until data[m] reaches the position i. for := ; > ; -- { .Swap(, -1) } return } := int(uint(+) >> 1) := + var , int if > { = - = } else { = = } := - 1 for < { := int(uint(+) >> 1) if !.Less(-, ) { = + 1 } else { = } } := - if < && < { rotate(, , , ) } if < && < { (, , , ) } if < && < { (, , , ) } } // rotate rotates two consecutive blocks u = data[a:m] and v = data[m:b] in data: // Data of the form 'x u v y' is changed to 'x v u y'. // rotate performs at most b-a many calls to data.Swap, // and it assumes non-degenerate arguments: a < m && m < b. func rotate( Interface, , , int) { := - := - for != { if > { swapRange(, -, , ) -= } else { swapRange(, -, +-, ) -= } } // i == j swapRange(, -, , ) } /* Complexity of Stable Sorting Complexity of block swapping rotation Each Swap puts one new element into its correct, final position. Elements which reach their final position are no longer moved. Thus block swapping rotation needs |u|+|v| calls to Swaps. This is best possible as each element might need a move. Pay attention when comparing to other optimal algorithms which typically count the number of assignments instead of swaps: E.g. the optimal algorithm of Dudzinski and Dydek for in-place rotations uses O(u + v + gcd(u,v)) assignments which is better than our O(3 * (u+v)) as gcd(u,v) <= u. Stable sorting by SymMerge and BlockSwap rotations SymMerg complexity for same size input M = N: Calls to Less: O(M*log(N/M+1)) = O(N*log(2)) = O(N) Calls to Swap: O((M+N)*log(M)) = O(2*N*log(N)) = O(N*log(N)) (The following argument does not fuzz over a missing -1 or other stuff which does not impact the final result). Let n = data.Len(). Assume n = 2^k. Plain merge sort performs log(n) = k iterations. On iteration i the algorithm merges 2^(k-i) blocks, each of size 2^i. Thus iteration i of merge sort performs: Calls to Less O(2^(k-i) * 2^i) = O(2^k) = O(2^log(n)) = O(n) Calls to Swap O(2^(k-i) * 2^i * log(2^i)) = O(2^k * i) = O(n*i) In total k = log(n) iterations are performed; so in total: Calls to Less O(log(n) * n) Calls to Swap O(n + 2*n + 3*n + ... + (k-1)*n + k*n) = O((k/2) * k * n) = O(n * k^2) = O(n * log^2(n)) Above results should generalize to arbitrary n = 2^k + p and should not be influenced by the initial insertion sort phase: Insertion sort is O(n^2) on Swap and Less, thus O(bs^2) per block of size bs at n/bs blocks: O(bs*n) Swaps and Less during insertion sort. Merge sort iterations start at i = log(bs). With t = log(bs) constant: Calls to Less O((log(n)-t) * n + bs*n) = O(log(n)*n + (bs-t)*n) = O(n * log(n)) Calls to Swap O(n * log^2(n) - (t^2+t)/2*n) = O(n * log^2(n)) */