github.com/primecitizens/pcz/std@v0.2.1/algo/sort/utils.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright 2023 The Prime Citizens
     3  
     4  package sort
     5  
     6  import (
     7  	"github.com/primecitizens/pcz/std/core/cmp"
     8  	"github.com/primecitizens/pcz/std/core/num"
     9  )
    10  
    11  func BuiltinLessFunc[T cmp.FOrdered](s []T, i, j int) bool {
    12  	return cmp.FLess(s[i], s[j])
    13  }
    14  
    15  func BuiltinCmpFunc[T num.Integer](s []T, i, j int) int {
    16  	return cmp.FCompare(s[i], s[j])
    17  }
    18  
    19  type ReverseSorter[T Interface] struct {
    20  	Inner T
    21  }
    22  
    23  // Len implements Interface
    24  func (r ReverseSorter[T]) Len() int { return r.Inner.Len() }
    25  
    26  // Swap implements Interface
    27  func (r ReverseSorter[T]) Swap(i int, j int) { r.Inner.Swap(i, j) }
    28  
    29  // Less returns the opposite of the embedded implementation's Less method.
    30  func (r ReverseSorter[T]) Less(i, j int) bool { return !r.Inner.Less(j, i) }
    31  
    32  type SliceSorter[Elem any] struct {
    33  	Data     []Elem
    34  	LessFunc func(data []Elem, i, j int) bool
    35  }
    36  
    37  // Len implements Interface
    38  func (s *SliceSorter[E]) Len() int { return len(s.Data) }
    39  
    40  // Less implements Interface
    41  func (s *SliceSorter[E]) Less(i, j int) bool { return s.LessFunc(s.Data, i, j) }
    42  
    43  // Swap implements Interface
    44  func (s *SliceSorter[E]) Swap(i, j int) { s.Data[i], s.Data[j] = s.Data[j], s.Data[i] }