English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
GoにはSortパッケージがあり、ビルトインおよびユーザー定義のデータタイプにソートを適用できます。
sortパッケージには異なるデータタイプにソートするための異なるメソッドがあります。例えばInts()、Float64s()、Strings()などを使用できます。
AreSorted()メソッド(例えばFloat64sAreSorted()、IntsAreSorted()などで値がソートされているかを確認します。
package main import ( "sort" "fmt" ) func main() { intValue := []int{10, 20, 5, 8} sort.Ints(intValue) fmt.Println("Ints: ", intValue) floatValue := []float64{10.5, 20.5, 5.5, 8.5} sort.Float64s(floatValue) fmt.Println("floatValue: ", floatValue) stringValue := []string{"Raj", "Mohan", "Roy"} sort.Strings(stringValue) fmt.Println("Strings:", stringValue) str := sort.Float64sAreSorted(floatValue) fmt.Println("Sorted: ", s
出力:
Ints:5 8 10 2[0] floatValue:5.5 8.5 10.5 20.5] Strings: [Raj Mohan Roy] Sorted: true
文字列の長さに基づいて文字列配列をソートしたい場合、独自のソートパターンを実装することもできます。そのために、ソートインターフェースで定義された独自のLess、Len、Swapメソッドを実装する必要があります。
それでは、配列を実装の型に変換する必要があります。
package main import "sort" import "fmt" type OrderByLengthDesc []string func (s OrderByLengthDesc) Len() int { return len(s) } func (str OrderByLengthDesc) Swap(i, j int) { str[i], str[j] = str[j], str[i] } func (s OrderByLengthDesc) Less(i, j int) bool { return len(s[i]) > len(s[j]) } func main() { city := []string{"ニューヨーク", "ロンドン","ワシントン","デリー"} sort.Sort(OrderByLengthDesc(city)) fmt.Println(city) }
出力:
[ワシントン ニューヨーク ロンドン デリー]