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 "math/bits"
     8  
     9  // Slice sorts the slice x given the provided less function.
    10  // It panics if x is not a slice.
    11  //
    12  // The sort is not guaranteed to be stable: equal elements
    13  // may be reversed from their original order.
    14  // For a stable sort, use SliceStable.
    15  //
    16  // The less function must satisfy the same requirements as
    17  // the Interface type's Less method.
    18  func Slice(x any, less func(i, j int) bool) {
    19  	rv := reflectValueOf(x)
    20  	swap := reflectSwapper(x)
    21  	length := rv.Len()
    22  	limit := bits.Len(uint(length))
    23  	pdqsort_func(lessSwap{less, swap}, 0, length, limit)
    24  }
    25  
    26  // SliceStable sorts the slice x using the provided less
    27  // function, keeping equal elements in their original order.
    28  // It panics if x is not a slice.
    29  //
    30  // The less function must satisfy the same requirements as
    31  // the Interface type's Less method.
    32  func SliceStable(x any, less func(i, j int) bool) {
    33  	rv := reflectValueOf(x)
    34  	swap := reflectSwapper(x)
    35  	stable_func(lessSwap{less, swap}, rv.Len())
    36  }
    37  
    38  // SliceIsSorted reports whether the slice x is sorted according to the provided less function.
    39  // It panics if x is not a slice.
    40  func SliceIsSorted(x any, less func(i, j int) bool) bool {
    41  	rv := reflectValueOf(x)
    42  	n := rv.Len()
    43  	for i := n - 1; i > 0; i-- {
    44  		if less(i, i-1) {
    45  			return false
    46  		}
    47  	}
    48  	return true
    49  }
    50  

View as plain text