1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

競プロで使うための GO 入門 ~ソート~

Last updated at Posted at 2020-07-18

Index

ソート

sortパッケージをインポートする

package main

import (
    "fmt"
    "sort" // sortパッケージ
)

func main() {

}

シンプルなソート

    s := []string{"e", "d", "c", "b", "a"}

    // 昇順
    sort.Sort(sort.StringSlice(s))

    fmt.Println(s) // ->[a b c d e]

    // 降順
    sort.Sort(sort.Reverse(sort.StringSlice(s)))

    fmt.Println(s) // ->[e d c b a]

構造体のソート

構造体をソートするためには、インターフェイスを実装する必要がある

package main

import (
	"fmt"
	"sort"
)

// 構造体
type Person struct {
	name string
	age  int
}

// 構造体のスライス
type People []Person

// sortインタフェース実装
func (p People) Len() int           { return len(p) }
func (p People) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p People) Less(i, j int) bool { return p[i].age < p[j].age }

func main() {
    var people People = []Person{{"A", 25}, {"B", 19}, {"C", 22}}
    sort.Sort(people)
    fmt.Println(people) // -> [{B 19} {C 22} {A 25}]
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?