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

# 線形探索ではなく2分木探索した方がいいサイズってどれくらいなのか

More than 3 years have passed since last update.

ふと思ったので調べてみた

catatsuy/linear_binary_compare

```package main

import (
"math/rand"
"testing"
"time"
)

const (
Size = 75
)

func BenchmarkLinearSearch(b *testing.B) {
b.StopTimer()

lists := make([]int, 0)
for i := 0; i < Size; i++ {
lists = append(lists, i)
}
rand.Seed(time.Now().UnixNano())

b.StartTimer()

for i := 0; i < b.N; i++ {
target := rand.Intn(len(lists))
for _, v := range lists {
if target == v {
break
}
}
}
}

func BenchmarkBinarySearch(b *testing.B) {
b.StopTimer()

lists := make([]int, 0)
for i := 0; i < Size; i++ {
lists = append(lists, i)
}
rand.Seed(time.Now().UnixNano())

b.StartTimer()

for i := 0; i < b.N; i++ {
start, end := 0, len(lists)-1
target := rand.Intn(len(lists))
for start <= end {
pivot := (start + end) / 2
if lists[pivot] < target {
start = pivot + 1
} else if lists[pivot] > target {
end = pivot - 1
} else {
break
}
}
}
}
```

こういうときにGoを使うの、サクッとかけるし正確なベンチが取れそうな気がする。

それとこれはあくまでも平均で、最悪実行時間は線形探索の方が遅いはずなので実際はこれよりも小さいサイズでも2分木探索の方が良いはず。

Why do not you register as a user and use Qiita more conveniently?
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