Hike News
Hike News

Go初識-day11-排序與查找

introduction

Go語言本身已有內置的官方package可無痛實現排序功能


Notice

  • 使用排序(sort)函數時,不能使用陣列作為排序的對象
  • 因陣列本身為值類型,傳參時為陣列的副本傳參,是對副本進行排序,不會對外部陣列排序
  • 必須為切片類型才能進行排序

排序整數

使用sort.Ints([]int)排序整數類型的切片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main

import (
"fmt"
"sort"
)

func IntSort(slice []int){
sort.Ints(slice) //*
return
}

func main(){
var list = [...]int{1,468,48,456,465,465,48,4,46,54,54,8,43,2,41,98,1,6,16,489,4689,788948,4689,489,4,}
IntSort(list[:]) //[1]
fmt.Println(list)
}

[1] 傳入list陣列的全切片

result

1
[1 1 2 4 4 6 8 16 41 43 46 48 48 54 54 98 456 465 465 468 489 489 4689 4689 788948]

切片是指向陣列的,可以發現陣列也發生了排序


排序字符串

使用sort.Strings([]string)排序字符串類型的切片

  • 默認是從ASCII碼由小到大排列
  • ASCII
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    package main

    import (
    "fmt"
    "sort"
    )

    func StringSort(slice []string){
    sort.Strings(slice) //*
    return
    }

    func main(){
    var list = [...]string{"Apple","banana","Cake","dog","EGG","elephant","Fox","@","*","&"," "}
    StringSort(list[:])
    fmt.Println(list)
    }

result

1
[  & * @ Apple Cake EGG Fox banana dog elephant]

排序浮點數

使用sort.Float64s([]float64)排序浮點數類型的切片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main

import (
"fmt"
"sort"
)

func FloatSort(slice []float64){
sort.Float64s(slice) //*
return
}

func main(){
var list = [...]float64{1531.6181,843.4848,0.484,6198.54984,0.000584894,0.00541818184}
FloatSort(list[:])
fmt.Println(list)
}

result

1
[0.000584894 0.00541818184 0.484 843.4848 1531.6181 6198.54984]

查找元素於切片的位置

sort包中有相關的search函數可以查找已排序的切片中特定元素位於切片中的index值

  • 要是傳入的切片未排序,會返回錯誤的index
  1. 查找string型,使用sort.SearchStrings
  2. 查找Int型,使用sort.SearchInts
  3. 查找float64型,使用sort.SearchFloat64s

以查找float64為範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
"fmt"
"sort"
)

func FloatSort(slice []float64){
sort.Float64s(slice) //*
return
}

func search(target float64,slice []float64)int{
return sort.SearchFloat64s(slice,target) //*
}

func main(){
var list = [...]float64{1531.6181,843.4848,0.484,6198.54984,0.000584894,0.00541818184}
FloatSort(list[:])
fmt.Println(list)
result := search(1531.6181,list[:])
fmt.Println("result =",result)
}

result

1
2
[0.000584894 0.00541818184 0.484 843.4848 1531.6181 6198.54984]
result = 4