SoFunction
Updated on 2025-03-06

Go language sorting and interface example analysis

import "fmt"
type Sorter interface {
  Len() int
  Less(i, j int) bool
  Swap(i, j int)
}
type Xi []int
type Xs []string
func (p Xi) Len() int { return len(p) }
func (p Xi) Less(i int, j int) bool { return p[j] < p[i] }
func (p Xi) Swap(i int, j int) { p[i], p[j] = p[j], p[i] }
func (p Xs) Len() int { return len(p) }
func (p Xs) Less(i int, j int) bool { return p[j] < p[i] }
func (p Xs) Swap(i int, j int) { p[i], p[j] = p[j], p[i] }
func Sort(x Sorter) {
  for i := 0; i < () - 1; i++ {
    for j := i + 1; j < (); j++ {
      if (i, j) {
        (i, j)
      }
    }
  }
}
func main() {
  ints := Xi{44, 67, 3, 17, 89, 10, 73, 9, 14, 8}
  strings := Xs{"nut", "ape", "elephant", "zoo", "go"}
  Sort(ints)
  ("%v\n", ints)
  Sort(strings)
  ("%v\n", strings)
}