codekingpro/portable-devtools
114k
1// Copyright 2017 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4 5package sort6 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 elements16// may be reversed from their original order.17// For a stable sort, use [SliceStable].18//19// The less function must satisfy the same requirements as20// the Interface type's Less method.21//22// Note: in many situations, the newer [slices.SortFunc] function is more23// 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 less33// 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 as37// the Interface type's Less method.38//39// Note: in many situations, the newer [slices.SortStableFunc] function is more40// 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 more51// 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 false58 }59 }60 return true61}62 