0
0

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 2021-05-19

簡単に調べて、Qiitaで見つからなかったので

参考文献

実装

package main

import (
	"math"
)

var a = [10]int{1, 14, 32, 51, 51, 51, 243, 419, 750, 910}

func abs(x int) int {
	return int(math.Abs(float64(x)))
}

func isOK(index, key int) bool {
	return a[index] >= key
}

func binarySearch(key int) int {
	ng := -1
	ok := len(a)

	for abs(ok-ng) > 1 {
		mid := (ok + ng) / 2

		if isOK(mid, key) {
			ok = mid
		} else {
			ng = mid
		}
	}
	return ok
}

func main() {
}

テスト

// データ
// var a = [10]int{1, 14, 32, 51, 51, 51, 243, 419, 750, 910}

func TestBinarySearch(t *testing.T) {
	// 範囲外(左端) 気になるなら期待値は -1 であるように実装を変えてもいいかも
	got := binarySearch(0)
	want := 0
	if got != want {
		t.Errorf("binarySearch() = %d, want %d", got, want)
	}
	// 範囲外(右端)
	got = binarySearch(911)
	want = 10
	if got != want {
		t.Errorf("binarySearch() = %d, want %d", got, want)
	}
	// 13が以上が条件を満たす。最小のindexは a[1] = 14 なので 1
	got = binarySearch(13)
	want = 1
	if got != want {
		t.Errorf("binarySearch() = %d, want %d", got, want)
	}
	// 14が以上が条件を満たす。最小のindexは a[1] = 14 なので 1
	got = binarySearch(14)
	want = 1
	if got != want {
		t.Errorf("binarySearch() = %d, want %d", got, want)
	}
	// 15が以上が条件を満たす。最小のindexは a[2] = 32 なので 2
	got = binarySearch(15)
	want = 2
	if got != want {
		t.Errorf("binarySearch() = %d, want %d", got, want)
	}
	// 51が以上が条件を満たす。a[x] = 51 な xの中で、最小のindexは 3
	got = binarySearch(51)
	want = 3
	if got != want {
		t.Errorf("binarySearch() = %d, want %d", got, want)
	}
}


付録: データを外だししたくない人向け

package main

import (
	"math"
)

func abs(x int) int {
	return int(math.Abs(float64(x)))
}

func isOK(a *[]int, index, key int) bool {
	return (*a)[index] >= key
}

func binarySearch(a *[]int, key int) int {
	ng := -1
	ok := len(*a)

	for abs(ok-ng) > 1 {
		mid := (ok + ng) / 2

		if isOK(a, mid, key) {
			ok = mid
		} else {
			ng = mid
		}
	}
	return ok
}

func main() {
	var a = []int{1, 14, 32, 51, 51, 51, 243, 419, 750, 910}
	println(binarySearch(&a, 51) == 3)
}

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?