golang 排序(int float64 string-ASSII struct )

注意:字符串排序是按照ASCII排序
package main

import (
	"fmt"
	"sort"
)

func main() {

	ints := []int{7, 3, 5, 2, 4, 1, 6, 9, 8}
	float64s := []float64{3.14, 2.8, 1.6, 0.4, 0.2, 6.5, 5.68}
	stringS := []string{"wo", "ai", "golang", "he", "c++"}

	//1. int  float64  string  升序
	sort.Ints(ints)
	sort.Float64s(float64s)
	sort.Strings(stringS) //ASCII

	fmt.Println("int 升序:", ints)         //[1 2 3 4 5 6 7 8 9]
	fmt.Println("float64 升序:", float64s) //[0.2 0.4 1.6 2.8 3.14 5.68 6.5]
	fmt.Println("string 升序:", stringS)   //[ai c++ golang he wo]

	//2. int  float64  string  降序
	sort.Sort(sort.Reverse(sort.IntSlice(ints)))
	sort.Sort(sort.Reverse(sort.Float64Slice(float64s)))
	sort.Sort(sort.Reverse(sort.StringSlice(stringS)))

	fmt.Println("int 降序:", ints)         //[9 8 7 6 5 4 3 2 1]
	fmt.Println("float64 降序:", float64s) //[6.5 5.68 3.14 2.8 1.6 0.4 0.2]
	fmt.Println("string 降序:", stringS)   //[wo he golang c++ ai]

	//3.结构体排序
	user := []struct {
		Name string
		Age  int
	}{
		{"Gopher", 7},
		{"Alice", 55},
		{"Vera", 24},
		{"Bob", 75},
	}

	// Name升序
	sort.Slice(user, func(i, j int) bool { return user[i].Name < user[j].Name })
	fmt.Println("name升序:", user) //[{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]

	// 年龄降序
	sort.Slice(user, func(i, j int) bool { return user[i].Age > user[j].Age })
	fmt.Println("age降序:", user) //[{Bob 75} {Alice 55} {Vera 24} {Gopher 7}]

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值