LoginSignup
1
1

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-04-19

以前、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しか対応してないっぽい。

1
1
2

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