1. 程式人生 > >【Go語言】基本型別排序和 slice 排序

【Go語言】基本型別排序和 slice 排序

Go 是通過 sort 包提供排序和搜尋,因為 Go 暫時不支援泛型(將來也不好說支不支援),所以,Go 的 sort 和 search 使用起來跟型別是有關的,或是需要像 c 一樣寫比較函式等,稍微顯得也不是很方便。

引言

Go 的排序思路和 C 和 C++ 有些差別。 C 預設是對陣列進行排序, C++ 是對一個序列進行排序, Go 則更寬泛一些,待排序的可以是任何物件, 雖然很多情況下是一個 slice (分片, 類似於陣列),或是包含 slice 的一個物件。

排序(介面)的三個要素:

  • 待排序元素個數 n ;
  • 第 i 和第 j 個元素的比較函式 cmp ;
  • 第 i 和 第 j 個元素的交換 swap ;

乍一看條件 3 是多餘的, c 和 c++ 都不提供 swap 。 c 的 qsort 的用法: qsort(data, n, sizeof(int), cmp_int); data 是起始地址, n 是元素個數, sizeof(int) 是每個元素的大小, cmp_int 是一個比較兩個 int 的函式。

c++ 的 sort 的用法: sort(data, data+n, cmp_int); data 是第一個元素的位置, data+n 是最後一個元素的下一個位置, cmp_int 是比較函式。

基本型別排序(int、float64 和 string)

1、升序排序

對於 int 、 float64 和 string 陣列或是分片的排序, go 分別提供了 sort.Ints() 、 sort.Float64s() 和 sort.Strings() 函式, 預設都是從小到大排序。

package main

import (
    "fmt"
    "sort"
)

func main() {
    intList := [] int {2, 4, 3, 5, 7, 6, 9, 8, 1, 0}
    float8List := [] float64 {4.2, 5.9, 12.3, 10.0, 50.4, 99.9, 31.4, 27.81828
, 3.14} stringList := [] string {"a", "c", "b", "d", "f", "i", "z", "x", "w", "y"} sort.Ints(intList) sort.Float64s(float8List) sort.Strings(stringList) fmt.Printf("%v\n%v\n%v\n", intList, float8List, stringList) }

2、降序排序

int 、 float64 和 string 都有預設的升序排序函式, 現在問題是如果降序如何 ? 有其他語言程式設計經驗的人都知道,只需要交換 cmp 的比較法則就可以了, go 的實現是類似的,然而又有所不同。 go 中對某個 Type 的物件 obj 排序, 可以使用 sort.Sort(obj) 即可,就是需要對 Type 型別繫結三個方法 : Len() 求長度、Less(i,j) 比較第 i 和 第 j 個元素大小的函式、 Swap(i,j) 交換第 i 和第 j 個元素的函式。sort 包下的三個型別 IntSliceFloat64SliceStringSlice 分別實現了這三個方法, 對應排序的是 [] int 、 [] float64 和 [] string 。如果期望逆序排序, 只需要將對應的 Less 函式簡單修改一下即可。

go 的 sort 包可以使用 sort.Reverse(slice) 來調換 slice.Interface.Less ,也就是比較函式,所以, int 、 float64 和 string 的逆序排序函式可以這麼寫:

package main

import (
    "fmt"
    "sort"
)

func main() {
    intList := [] int {2, 4, 3, 5, 7, 6, 9, 8, 1, 0}
    float8List := [] float64 {4.2, 5.9, 12.3, 10.0, 50.4, 99.9, 31.4, 27.81828, 3.14}
    stringList := [] string {"a", "c", "b", "d", "f", "i", "z", "x", "w", "y"}

    sort.Sort(sort.Reverse(sort.IntSlice(intList)))
    sort.Sort(sort.Reverse(sort.Float64Slice(float8List)))
    sort.Sort(sort.Reverse(sort.StringSlice(stringList)))

    fmt.Printf("%v\n%v\n%v\n", intList, float8List, stringList)
}

3、深入理解排序

sort 包中有一個 sort.Interface 介面,該介面有三個方法 Len() 、 Less(i,j) 和 Swap(i,j) 。 通用排序函式 sort.Sort 可以排序任何實現了 sort.Inferface 介面的物件(變數)。對於 [] int 、[] float64 和 [] string 除了使用特殊指定的函式外,還可以使用改裝過的型別 IntSclice 、 Float64Slice 和 StringSlice , 然後直接呼叫它們對應的 Sort() 方法;因為這三種類型也實現了 sort.Interface 介面, 所以可以通過 sort.Reverse 來轉換這三種類型的 Interface.Less 方法來實現逆向排序, 這就是前面最後一個排序的使用。

下面使用了一個自定義(使用者定義)的 Reverse 結構體, 而不是 sort.Reverse 函式, 來實現逆向排序。

package main

import (
    "fmt"
    "sort"
)

// 自定義的 Reverse 型別
type Reverse struct {
    sort.Interface    // 這樣,Reverse可以接納任何實現了sort.Interface的物件
}

// Reverse 只是將其中的 Inferface.Less 的順序對調了一下
func (r Reverse) Less(i, j int) bool {
    return r.Interface.Less(j, i)
}

func main() {
    ints := []int{5, 2, 6, 3, 1, 4}

    sort.Ints(ints)                                     // 特殊排序函式,升序
    fmt.Println("after sort by Ints:\t", ints)

    doubles := []float64{2.3, 3.2, 6.7, 10.9, 5.4, 1.8}

    sort.Float64s(doubles)
    fmt.Println("after sort by Float64s:\t", doubles)   // [1.8 2.3 3.2 5.4 6.7 10.9]

    strings := []string{"hello", "good", "students", "morning", "people", "world"}
    sort.Strings(strings)
    fmt.Println("after sort by Strings:\t", strings)    // [good hello mornig people students world]

    ipos := sort.SearchInts(ints, -1)    // int 搜尋
    fmt.Printf("pos of 5 is %d th\n", ipos)

    dpos := sort.SearchFloat64s(doubles, 20.1)    // float64 搜尋
    fmt.Printf("pos of 5.0 is %d th\n", dpos)

    fmt.Printf("doubles is asc ? %v\n", sort.Float64sAreSorted(doubles))

    doubles = []float64{3.5, 4.2, 8.9, 100.98, 20.14, 79.32}
    // sort.Sort(sort.Float64Slice(doubles))    // float64 排序方法 2
    // fmt.Println("after sort by Sort:\t", doubles)    // [3.5 4.2 8.9 20.14 79.32 100.98]
    (sort.Float64Slice(doubles)).Sort()         // float64 排序方法 3
    fmt.Println("after sort by Sort:\t", doubles)       // [3.5 4.2 8.9 20.14 79.32 100.98]

    sort.Sort(Reverse{sort.Float64Slice(doubles)})    // float64 逆序排序
    fmt.Println("after sort by Reversed Sort:\t", doubles)      // [100.98 79.32 20.14 8.9 4.2 3.5]
}

sort.Ints / sort.Float64s / sort.Strings 分別來對整型/浮點型/字串型slice進行排序。然後是有個測試是否有序的函式。還有分別對應的 search 函式,不過,發現搜尋函式只能定位到如果存在的話的位置,不存在的話,位置是不對的。

關於一般的陣列排序,程式中顯示了,有 3 種方法!目前提供的三種類型 int,float64 和 string 呈現對稱的,也就是你有的,對應的我也有。關於翻轉排序或是逆向排序,就是用個翻轉結構體,重寫 Less() 函式即可。上面的 Reverse 是個通用的結構體。

上面說了那麼多, 只是對基本型別進行排序, 該到說說 struct 結構體型別的排序的時候了, 實際中這個用得到的會更多。

結構體型別的排序

結構體型別的排序是通過使用 sort.Sort(slice) 實現的, 只要 slice 實現了 sort.Interface 的三個方法就可以。 雖然這麼說,但是排序的方法卻有那麼好幾種。首先一種就是模擬排序 [] int 構造對應的 IntSlice 型別,然後對 IntSlice 型別實現 Interface 的三個方法。

1、模擬 IntSlice 排序

package main

import (
    "fmt"
    "sort"
)

type Person struct {
    Name string
    Age  int
}

// 按照 Person.Age 從大到小排序
type PersonSlice [] Person

func (a PersonSlice) Len() int {         // 重寫 Len() 方法
    return len(a)
}
func (a PersonSlice) Swap(i, j int){     // 重寫 Swap() 方法
    a[i], a[j] = a[j], a[i]
}
func (a PersonSlice) Less(i, j int) bool {    // 重寫 Less() 方法, 從大到小排序
    return a[j].Age < a[i].Age
}

func main() {
    people := [] Person{
        {"zhang san", 12},
        {"li si", 30},
        {"wang wu", 52},
        {"zhao liu", 26},
    }

    fmt.Println(people)

    sort.Sort(PersonSlice(people))    // 按照 Age 的逆序排序
    fmt.Println(people)

    sort.Sort(sort.Reverse(PersonSlice(people)))    // 按照 Age 的升序排序
    fmt.Println(people)

}

這完全是一種模擬的方式,所以如果懂了 IntSlice 自然就理解這裡了,反過來,理解了這裡那麼 IntSlice 那裡也就懂了。

這種方法的缺點是:根據 Age 排序需要重新定義 PersonSlice 方法,繫結 Len 、 Less 和 Swap 方法, 如果需要根據 Name 排序, 又需要重新寫三個函式; 如果結構體有 4 個欄位,有四種類型的排序,那麼就要寫 3 × 4 = 12 個方法, 即使有一些完全是多餘的, O__O”… 仔細思量一下,根據不同的標準 Age 或是 Name, 真正不同的體現在 Less 方法上,所以可以將 Less 抽象出來, 每種排序的 Less 讓其變成動態的,比如下面一種方法。

2、封裝成 Wrapper

package main

import (
    "fmt"
    "sort"
)

type Person struct {
    Name string
    Age  int
}

type PersonWrapper struct {                 //注意此處
    people [] Person
    by func(p, q * Person) bool
}

func (pw PersonWrapper) Len() int {         // 重寫 Len() 方法
    return len(pw.people)
}
func (pw PersonWrapper) Swap(i, j int){     // 重寫 Swap() 方法
    pw.people[i], pw.people[j] = pw.people[j], pw.people[i]
}
func (pw PersonWrapper) Less(i, j int) bool {    // 重寫 Less() 方法
    return pw.by(&pw.people[i], &pw.people[j])
}

func main() {
    people := [] Person{
        {"zhang san", 12},
        {"li si", 30},
        {"wang wu", 52},
        {"zhao liu", 26},
    }

    fmt.Println(people)

    sort.Sort(PersonWrapper{people, func (p, q *Person) bool {
        return q.Age < p.Age    // Age 遞減排序
    }})

    fmt.Println(people)
    sort.Sort(PersonWrapper{people, func (p, q *Person) bool {
        return p.Name < q.Name    // Name 遞增排序
    }})

    fmt.Println(people)

}

這種方法將 [] Person 和比較的準則 cmp 封裝在了一起,形成了 PersonWrapper 函式,然後在其上繫結 Len 、 Less 和 Swap 方法。 實際上 sort.Sort(pw) 排序的是 pw 中的 people, 這就是前面說的, go 的排序未必就是針對的一個數組或是 slice, 而可以是一個物件中的陣列或是 slice

3、進一步封裝

感覺方法 2 已經很不錯了, 唯一一個缺點是,在 main 中使用的時候暴露了 sort.Sort 的使用,還有就是 PersonWrapper 的構造。 為了讓 main 中使用起來更為方便, me 們可以再簡單的封裝一下, 構造一個 SortPerson 方法, 如下:

package main

import (
    "fmt"
    "sort"
)

type Person struct {
    Name string
    Age  int
}

type PersonWrapper struct {
    people [] Person
    by func(p, q * Person) bool
}

type SortBy func(p, q *Person) bool

func (pw PersonWrapper) Len() int {         // 重寫 Len() 方法
    return len(pw.people)
}
func (pw PersonWrapper) Swap(i, j int){     // 重寫 Swap() 方法
    pw.people[i], pw.people[j] = pw.people[j], pw.people[i]
}
func (pw PersonWrapper) Less(i, j int) bool {    // 重寫 Less() 方法
    return pw.by(&pw.people[i], &pw.people[j])
}

// 封裝成 SortPerson 方法
func SortPerson(people [] Person, by SortBy){
    sort.Sort(PersonWrapper{people, by})
}

func main() {
    people := [] Person{
        {"zhang san", 12},
        {"li si", 30},
        {"wang wu", 52},
        {"zhao liu", 26},
    }

    fmt.Println(people)

    sort.Sort(PersonWrapper{people, func (p, q *Person) bool {
        return q.Age < p.Age    // Age 遞減排序
    }})

    fmt.Println(people)

    SortPerson(people, func (p, q *Person) bool {
        return p.Name < q.Name    // Name 遞增排序
    })

    fmt.Println(people)

}

在方法 2 的基礎上構造了 SortPerson 函式,使用的時候傳過去一個 [] Person 和一個 cmp 函式。

4、另一種思路

package main

import (
    "fmt"
    "sort"
)

type Person struct {
    Name        string
    Weight      int
}

type PersonSlice []Person

func (s PersonSlice) Len() int  { return len(s) }
func (s PersonSlice) Swap(i, j int)     { s[i], s[j] = s[j], s[i] }

type ByName struct{ PersonSlice }    // 將 PersonSlice 包裝起來到 ByName 中

func (s ByName) Less(i, j int) bool     { return s.PersonSlice[i].Name < s.PersonSlice[j].Name }    // 將 Less 繫結到 ByName 上


type ByWeight struct{ PersonSlice }    // 將 PersonSlice 包裝起來到 ByWeight 中
func (s ByWeight) Less(i, j int) bool   { return s.PersonSlice[i].Weight < s.PersonSlice[j].Weight }    // 將 Less 繫結到 ByWeight 上

func main() {
    s := []Person{
        {"apple", 12},
        {"pear", 20},
        {"banana", 50},
        {"orange", 87},
        {"hello", 34},
        {"world", 43},
    }

    sort.Sort(ByWeight{s})
    fmt.Println("People by weight:")
    printPeople(s)

    sort.Sort(ByName{s})
    fmt.Println("\nPeople by name:")
    printPeople(s)

}

func printPeople(s []Person) {
    for _, o := range s {
        fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)
    }
}

對結構體的排序, 暫時就到這裡。 第一種排序對只根據一個欄位的比較合適, 另外三個是針對可能根據多個欄位排序的。方法 4 我認為每次都要多構造一個 ByXXX , 頗為不便, 這樣多麻煩,不如方法 2 和方法 3 來的方便,直接傳進去一個 cmp。 方法2、 3 沒有太大的差別, 3 只是簡單封裝了一下而已, 對於使用者來說, 可能會更方便一些,而且也會更少的出錯。

參考資料: