Go 对Map字段进行排序,使用冒泡排序对map指定的key进行排序

732人浏览 2022-08-26

Go 对Map字段进行排序,使用冒泡排序对map指定的key进行排序

代码: 

// BubbleSortMapData 冒泡排序[]map[string]interface{}
// wait 等待排序的map 指针类型
// key 需要排序的key 对应map里的字段 如 map["id"]10里的 id
// desc 是否为desc 排序
func BubbleSortMapData(wait *[]map[string]interface{}, key string, desc bool) {
	for i := 0; i < len(*wait)-1; i++ {
		for j := 0; j < len(*wait)-1-i; j++ {
			t1 := (*wait)[j]
			t1Val, _ := strconv.ParseFloat(fmt.Sprintf("%v", t1[key]), 64)
			t2Val, _ := strconv.ParseFloat(fmt.Sprintf("%v", ((*wait)[j+1])[key]), 64)
			if desc {
				if t2Val > t1Val { //交换
					(*wait)[j] = (*wait)[j+1]
					(*wait)[j+1] = t1
				}
			} else {
				if t2Val < t1Val { //交换
					(*wait)[j] = (*wait)[j+1]
					(*wait)[j+1] = t1
				}
			}
		}
	}
}

 

推荐文章

GORM 自定义结构体关联的数据库表名称和自定义结构体字段对应的数据表字段名
2021-02-23
KChatRoom在线多人聊天室,项目是使用Websocket和Gin框架基于Golang开发的在线聊天室
2021-05-17
Gin框架下获取所有路由信息
2021-07-14
搜索文章