BasegoSort

BasegoSort

直接传引用类型就可以,不用地址

stand_sort.go

package stand_sort

import (
	"fmt"
	"sort"
)

type Person struct {
	Name string
	Age  int
}

func (p Person) String() string {
	return fmt.Sprintf("%s: %d", p.Name, p.Age)
}

// ByAge implements sort.Interface for []Person based on
// the Age field.
type ByAge []Person

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }

func StandExample() {
	people := []Person{
		{"Bob", 31},
		{"John", 42},
		{"Michael", 17},
		{"Jenny", 26},
	}

	fmt.Println(people)
	// There are two ways to sort a slice. First, one can define
	// a set of methods for the slice type, as with ByAge, and
	// call sort.Sort. In this first example we use that technique.
	sort.Sort(ByAge(people))
	fmt.Println(people)

	// The other way is to use sort.Slice with a custom Less
	// function, which can be provided as a closure. In this
	// case no methods are needed. (And if they exist, they
	// are ignored.) Here we re-sort in reverse order: compare
	// the closure with ByAge.Less.
	sort.Slice(people, func(i, j int) bool {
		return people[i].Age > people[j].Age
	})
	fmt.Println(people)

}

func IntSliceSort(s []int) {
	sort.Ints(s)
}

// less func 排序
func SliceLess() {
	people := []struct {
		Name string
		Age  int
	}{
		{"Gopher", 7},
		{"Alice", 55},
		{"Vera", 24},
		{"Bob", 75},
	}
	sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
	fmt.Println("By name:", people)

	sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
	fmt.Println("By age:", people)
}

// int slice排序
// > 是降序
// < 是升序
func IntSliceLess(arr []int) {
	sort.Slice(arr, func(i, j int) bool {
		return  arr[i] > arr[j]
	})
}

test.go

package stand_sort

import (
	"fmt"
	"testing"
)

func TestStandExample(t *testing.T) {
	// 标准sort
	//StandExample()

	// 整型切片排序
	// 从小到大输出
	//start := time.Now()
	//var s []int
	//s = append(s, 1,5, 2, 99, 66)
	//IntSliceSort(s)
	//fmt.Println(s)
	//since := time.Since(start)
	//fmt.Println(since)

	//SliceLess()

	// int slice less
	var s []int
	s = append(s, 1,5, 2, 99, 66)
	IntSliceLess(s)
	fmt.Println(s)
}

小结

最舒服的用法,因为下面可以是任意类型数据

// int slice排序
// > 是降序
// < 是升序
func IntSliceLess(arr []int) {
	sort.Slice(arr, func(i, j int) bool {
		return  arr[i] > arr[j]
	})
}
posted @ 2020-12-12 20:11  maob  阅读(60)  评论(0编辑  收藏  举报