Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

sort.SearchInts()はSort済みじゃないと動かない

以前、PHPを使っていたので、Goにも配列検索してくれる関数無いかな〜って思って調べたらそれっぽい関数が!!

>>>sort.SearchInts()<<<

sortパッケージってのが気になるけど・・・嬉々として試してみる。

search1.go
package main

import (
    "fmt"
    "sort"
)

func main() {
    a := []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
    res := sort.SearchInts(a, 7)
    fmt.Println("array:", a)
    fmt.Println("result:", res)
}

Go Playground

結果

array: [10 9 8 7 6 5 4 3 2 1]
result: 10

はぁ?
なんでやねん!7の添字は0、1、2、3、、、3やろ!

読めない英語のリファレンスを頑張って見ていると、

SearchInts searches for x in a sorted slice of ints and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order.

ん?

in a sorted slice

まさかと思い、sort.Ints(a)でソートしてからSearchIntsしてみる

search2.go
package main

import (
    "fmt"
    "sort"
)

func main() {
    a := []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
    sort.Ints(a)
    res := sort.SearchInts(a, 7)
    fmt.Println("array:", a)
    fmt.Println("result:", res)
}

Go Playground

結果

array: [1 2 3 4 5 6 7 8 9 10]
result: 6

できた。

sortパッケージだからか、sortした後のsearchしか対応してないっぽい。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?