Go陣列遍歷與排序

2021-09-24 14:33:38 字數 1222 閱讀 8797

目錄

遍歷陣列

陣列排序

go遍歷陣列有兩種方式

1.按照陣列下標進行遍歷

2.用range遍歷

package main

import (

"fmt"

)func main()

// 方法一:直接用陣列下標遍歷

for i := 0; i < len(array); i++

fmt.println()

// 方法二:用range遍歷

for _, value := range array

}

go分別提供了sort.float64s()  sort.strings()  sort.ints() 對不同型別的陣列進行排序,預設是公升序。

降序需要使用sort.reverse

package main

import (

"fmt"

"sort"

)func main()

arrayfloat := float64

arraystring := string

// 公升序

sort.ints(arrayint)

sort.float64s(arrayfloat)

sort.strings(arraystring)

fmt.println("sort int:", arrayint)

fmt.println("sort float:", arrayfloat)

fmt.println("sort ", arraystring)

// 降序

sort.sort(sort.reverse(sort.intslice(arrayint)))

sort.sort(sort.reverse(sort.float64slice(arrayfloat)))

sort.sort(sort.reverse(sort.stringslice(arraystring)))

fmt.println("after reversed: ")

fmt.println("sort int:", arrayint)

fmt.println("sort float:", arrayfloat)

fmt.println("sort ", arraystring)

}

陣列遍歷排序

集合的遍歷 nsset 集合 nsdictionary dictionary nsdictionary dictionarywithobjectsandkeys 11 a 22 b 33 c nil nslog dictionary for int i 0 i dictionary.count i ...

6 go陣列與氣泡排序

陣列的概念 如何定義陣列 陣列常用的用法 陣列如何指定下標設值 二維陣列 氣泡排序 陣列 定義陣列 不同長度的陣列不可以互相定義,否則編譯會報錯的 如下的 func main 如果長度相同的兩個陣列,那麼可以互相賦值func main 不同型別的陣列之間也不可以互相賦值 如果定義陣列的時候沒有設值,...

6 go陣列與氣泡排序

陣列的概念 如何定義陣列 陣列常用的用法 陣列如何指定下標設值 二維陣列 氣泡排序 陣列定義陣列 不同長度的陣列不可以互相定義,否則編譯會報錯的 如下的 func main 如果長度相同的兩個陣列,那麼可以互相賦值func main 不同型別的陣列之間也不可以互相賦值 如果定義陣列的時候沒有設值,那...