Source file src/sort/slice.go

     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  
     5  package sort
     6  
     7  import (
     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  func Slice(x any, less func(i, j int) bool) {
    22  	rv := reflectlite.ValueOf(x)
    23  	swap := reflectlite.Swapper(x)
    24  	length := rv.Len()
    25  	limit := bits.Len(uint(length))
    26  	pdqsort_func(lessSwap{less, swap}, 0, length, limit)
    27  }
    28  
    29  // SliceStable sorts the slice x using the provided less
    30  // function, keeping equal elements in their original order.
    31  // It panics if x is not a slice.
    32  //
    33  // The less function must satisfy the same requirements as
    34  // the Interface type's Less method.
    35  func SliceStable(x any, less func(i, j int) bool) {
    36  	rv := reflectlite.ValueOf(x)
    37  	swap := reflectlite.Swapper(x)
    38  	stable_func(lessSwap{less, swap}, rv.Len())
    39  }
    40  
    41  // SliceIsSorted reports whether the slice x is sorted according to the provided less function.
    42  // It panics if x is not a slice.
    43  func SliceIsSorted(x any, less func(i, j int) bool) bool {
    44  	rv := reflectlite.ValueOf(x)
    45  	n := rv.Len()
    46  	for i := n - 1; i > 0; i-- {
    47  		if less(i, i-1) {
    48  			return false
    49  		}
    50  	}
    51  	return true
    52  }
    53  

View as plain text