golang sort包的使用(一)

一、包说明

这个包是一个golang内置的切片排序包,除了排序外还有一些其它的方法,可以对一些基本的可以比较大小的类型的切片进行排序,也可以通过实现排序接口的几个特定方法实现自定义排序。

二、简单的使用方法

1、可以使用sort.Ints()、sort.Strings()等内置方法对基本数据类型的切片进行排序

/*
 * Author:  oy
 * Email:   oyblog@qq.com
 * Date:    2021/6/2 下午7:10
 */
package UnitTest

import (
	"fmt"
	"sort"
	"testing"
)

func TestSort(t *testing.T) {
	ints := []int{3, 2, 1}
	strs := []string{"c", "d", "a"}
	sort.Strings(strs)
	sort.Ints(ints)
	fmt.Printf("%v
", ints)
	fmt.Printf("%v
", strs)
}

[1 2 3]
[a c d]

2、因为切片属于引用类型,所以我们只需要将需要排序的切片传给排序方法就可以了不需要写成sort.Strings(&strs) strs = sort.Strings(strs) ,这两种写法都会导致编译失败,使用方式很简单这里不再做过多说明。

三、自定义排序

1、sort.Ints()sort.Strings()等方法都是按升序排序的,如果我们希望按降序排序就需要我们自定义排序规则,自定义排序需要我们实现接口的Len()Less(i,j int)Swap(i,j int)这三个方法。主要是实现Less(i,j int)方法,这个方法里面写排序算法(两个元素比较大小的方式),Len() 方法是用来计算切片长度的直接return len(data)就可以了,Swap(i,j int) 这个方法在调用排序方法后调换两个元素的位置可以写死成 ints[i], ints[j] = ints[j], ints[i],当Less()返回True 时就会调用Swap() 方法,调换两个相邻元素的位置。

// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
type Interface interface {
	// Len is the number of elements in the collection.
	Len() int
	// Less reports whether the element with
	// index i should sort before the element with index j.
	Less(i, j int) bool    //  i>j 元素i在元素j的前面
	// Swap swaps the elements with indexes i and j.
	Swap(i, j int)
}

2、对int切片按降序排序

/*
* email:   oyblog@qq.com
* Author:  oy
* Date:    2021/6/2 下午7:10
 */
package UnitTest

import (
	"fmt"
	"sort"
	"testing"
)

type IntList []int

func (ints IntList) Len() int {
	return len(ints)
}

func (ints IntList) Less(i, j int) bool {  //返回True时会调用Swap方法调换两个元素的位置
	return ints[i] > ints[j]   // (i>j),ints[i] < ints[j] 表示按升序排序,ints[i] > ints[j] 表示按降序排序
}

func (ints IntList) Swap(i, j int) {
	ints[i], ints[j] = ints[j], ints[i]
}

func TestSort(t *testing.T) {
	ints := IntList{}
	ints = []int{1, 2, 3, 4, 56, 6}
	sort.Sort(ints)
	fmt.Printf("%v
", ints)
}

=== RUN   TestSort
[56 6 4 3 2 1]
--- PASS: TestSort (0.00s)
PASS

四、使用心得

1、sort.Strings()方法并不能对字符串数字排序,虽然不会报错但是结果是错的,貌似是以字符串的第一位排的
2、应用场景,固定排序。

ghghgjhgjhgh
原文地址:https://www.cnblogs.com/just-do/p/14842849.html