使用golang的sort包進行排序

這是在掘金的第一篇文章,以前一直在某書發文章,進來感受某書愈來愈很差了,想把文章 都搬到掘金來。
java

介紹

golang和java等語言同樣,系統自帶了一個排序方法,能夠快速實現排序。廢話很少說,先上栗子,再解釋。
golang

package main

import (
	"fmt"
	"math/rand"
	"sort"
	"strconv"
)

func main() {
	oneArr := make([]*One, 10)
	for i := 0; i < 10; i++ {
		oneArr[i] = &One{
			Name: "name" + strconv.FormatInt(int64(i), 10),
			Num:  rand.Intn(1000),
		}
	}

	for _, v := range oneArr {
		fmt.Print(v, " ")
	}
	fmt.Println()
	sort.Sort(OneList(oneArr))
	for _, v := range oneArr {
		fmt.Print(v, " ")
	}
	fmt.Println()

}

type One struct {
	Num  int
	Name string
}

type OneList []*One

func (this OneList) Len() int {
	return len(this)
}
func (this OneList) Less(i, j int) bool {
	return this[i].Num < this[j].Num
}
func (this OneList) Swap(i, j int) {
	this[i], this[j] = this[j], this[i]
}
複製代碼

運行結果

運行結果
實現從小到大排序

解釋

使用type定義了一個 []*One 類型的OneList切片。OneLiit 實現Interface 這個接口 這個接口在sort 中定義,原型
bash

// 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
	// Swap swaps the elements with indexes i and j.
	Swap(i, j int)
}
複製代碼
  • Len() 函數 返回要排序的序列的長度
  • Less() 函數 返回排序須要的比較的規則,若是符合這個規則,就進行交換
  • Swap() 函數 進行排序的交換規則

OneList 重寫這3個函數
函數

新建一個切片oneArr,隨機填充數據,而後調用sort包中的Sort()函數,進行排序。
Sort()函數須要傳遞一個Interface 類型的參數。 使用強制類型轉換把 oneArr 轉換爲Interface類型。
ui

sort包中 還有一個函數實現反向排序,sort.sort.Reverse()能夠實現倒序排序
this

栗子 sort.Sort(sort.Reverse(OneList(oneArr))) 就能實現反向排序
結果: spa

實現從大到下排序

拓展

golang的sort包中爲咱們定義了一些經常使用的排序類型code

  • type IntSlice []int int類型切片的排序
  • type Float64Slice []float64 float64 類型切片的排序
  • type StringSlice []string string 類型切片的排序

看一個應用栗子:orm

package main

import (
	"fmt"
	"math/rand"
	"sort"
)

func main() {
	one := make([]int, 10)
	for i := 0; i < 10; i++ {
		one[i] = int(rand.Int31n(1000))
	}
	fmt.Println(one)
	sort.Sort(sort.IntSlice(one))
	fmt.Println(one)

}
複製代碼

運行結果:cdn

好了,先介紹到這裏。

相關文章
相關標籤/搜索