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{"라지", "모한", "로이"} sort.Strings(stringValue) fmt.Println("문자열:", stringValue) str := sort.Float64sAreSorted(floatValue) fmt.Println("정렬됨: ", s
출력:
Ints: [5 8 10 20] floatValue: [5.5 8.5 10.5 20.5] 문자열: [모한 라지 로이] 정렬됨: 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{"뉴욕", "런던", "워싱턴DC", "델리"} sort.Sort(OrderByLengthDesc(city)) fmt.Println(city) }
출력:
[워싱턴DC 뉴욕 런던 델리]