1// Copyright 2017 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 5package sort 6 7import ( 8 "internal/reflectlite" 9 "math/bits" 10) 11 12// Slice sorts the slice x given the provided less function. 13// It panics if x is not a slice. 14// 15// The sort is not guaranteed to be stable: equal elements 16// may be reversed from their original order. 17// For a stable sort, use [SliceStable]. 18// 19// The less function must satisfy the same requirements as 20// the Interface type's Less method. 21// 22// Note: in many situations, the newer [slices.SortFunc] function is more 23// ergonomic and runs faster. 24func Slice(x any, less func(i, j int) bool) { 25 rv := reflectlite.ValueOf(x) 26 swap := reflectlite.Swapper(x) 27 length := rv.Len() 28 limit := bits.Len(uint(length)) 29 pdqsort_func(lessSwap{less, swap}, 0, length, limit) 30} 31 32// SliceStable sorts the slice x using the provided less 33// function, keeping equal elements in their original order. 34// It panics if x is not a slice. 35// 36// The less function must satisfy the same requirements as 37// the Interface type's Less method. 38// 39// Note: in many situations, the newer [slices.SortStableFunc] function is more 40// ergonomic and runs faster. 41func SliceStable(x any, less func(i, j int) bool) { 42 rv := reflectlite.ValueOf(x) 43 swap := reflectlite.Swapper(x) 44 stable_func(lessSwap{less, swap}, rv.Len()) 45} 46 47// SliceIsSorted reports whether the slice x is sorted according to the provided less function. 48// It panics if x is not a slice. 49// 50// Note: in many situations, the newer [slices.IsSortedFunc] function is more 51// ergonomic and runs faster. 52func SliceIsSorted(x any, less func(i, j int) bool) bool { 53 rv := reflectlite.ValueOf(x) 54 n := rv.Len() 55 for i := n - 1; i > 0; i-- { 56 if less(i, i-1) { 57 return false 58 } 59 } 60 return true 61} 62