Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

以前、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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした