go語言的排序和搜尋

來源:互聯網
上載者:User

標籤:

晚上準備動手寫點 go 的程式的時候,想起 go 如何排序的問題。排序 sort 是個基本的操作,當然搜尋 search 也是。c 提供一個 qsort 和 bsearch,一個快排一個二分尋找,不過是使用起來都不方便; c++ 中的 sort 貌似很不錯,因為 c++ 支援泛型(或是說模板),所以很多東西使用起來很方便。go 是通過 sort 包提供排序和搜尋,因為 go 暫時不支援泛型(將來也不好說支不支援),所以,go 的 sort 和 search 使用起來跟類型是有關的,或是需要像 c 一樣寫比較函數等,稍微顯得也不是很方便。


補註: 近來又看 go 的排序, 發現以前對 go 的排序理解的有點淺了。 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 的排序
升序排序
對於 int 、 float64 和 string 數組或是分區的排序, go 分別提供了 sort.Ints() 、 sort.Float64s() 和 sort.Strings() 函數, 預設都是從小到大排序。(沒有 sort.Float32s() 函數, me 頗有點奇怪。)


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}
    // float4List := [] float32 {4.2, 5.9, 12.3, 10.0, 50.4, 99.9, 31.4, 27.81828, 3.14}    // no function : sort.Float32s
    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)
 
}
降序排序
int 、 float64 和 string 都有預設的升序排序函數, 現在問題是如果降序如何 ? 有其他語言編程經驗的人都知道,只需要交換 cmp 的比較法則就可以了, go 的實現是類似的,然而又有所不同。 go 中對某個 Type 的對象 obj 排序, 可以使用 sort.Sort(obj) 即可,就是需要對 Type 類型綁定三個方法 : Len() 求長度、 Less(i,j) 比較第 i 和 第 j 個元素大小的函數、 Swap(i,j) 交換第 i 和第 j 個元素的函數。sort 包下的三個類型 IntSlice 、 Float64Slice 、 StringSlice 分別實現了這三個方法, 對應排序的是 [] 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)
}
深入理解排序
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 (包括 Len, Less, Swap 三個方法) 的對象
}
 
// 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)  // [1 2 3 4 5 6]
 
    doubles := []float64{2.3, 3.2, 6.7, 10.9, 5.4, 1.8}
 
    sort.Float64s(doubles)                                      // float64 排序版本 1
    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 分別來對整型/浮點型/字串型分區或是叫做片段,或是不嚴格滴說是數組,進行排序。然後是有個測試是否有序的函數。還有分別對應的 search 函數,不過,發現搜尋函數只能定位到如果存在的話的位置,不存在的話,位置就是不對的。


關於一般的數組排序,程式中顯示了,有 3 種方法!目前提供的三種類型 int,float64 和 string 呈現對稱的,也就是你有的,對應的我也有。


關於翻轉排序或是逆向排序,就是用個翻轉結構體,重寫 Less 函數即可。上面的 Reverse 是個通用的結構體。


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


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


結構體排序方法 1
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 那裡也就懂了。


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


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)
 
}
方法 2 將 [] Person 和比較的準則 cmp 封裝在了一起,形成了 PersonWrapper 函數,然後在其上綁定 Len 、 Less 和 Swap 方法。 實際上 sort.Sort(pw) 排序的是 pw 中的 people, 這就是前面說的, go 的排序未必就是針對的一個數組或是 slice, 而可以是一個對象中的數組或是 slice 。


結構體排序方法 3
me 趕腳方法 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])
}
 
 
func SortPerson(people [] Person, by SortBy){    // SortPerson 方法
    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
下面是另外一個實現思路, 可以說是方法 1、 2 的變體。


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 me 認為每次都要多構造一個 ByXXX , 頗為不便, 這樣多麻煩,不如方法 2 和方法 3 來的方便,直接傳進去一個 cmp ,然後 okay 。 2、 3 沒有太大的差別, 3 只是簡單封裝了一下而已, 對於使用者來說, 可能會更方便一些,而且也會更少的出錯。


關於 go 的排序還沒有結束, 如果 u 已經累了, 就歇歇去吧, =_=

go語言的排序和搜尋

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.