LoginSignup
0
2

More than 5 years have passed since last update.

Goでのアルゴリズムクイックリファレンス第2版(逐次探索)

Posted at

Goに慣れるためとアルゴリズムの復習の為に週1ぐらいで更新していきます。アルゴリズムクイックリファレンス 第2版を読んで各種アルゴリズムをGoで実装して行きます。

前回: Goでのアルゴリズムクイックリファレンス第2版(マージソート)

今回は逐次探索

集まりCのなかの目標値tを力任せで見つける。最良でO(1)で平均・最悪O(n)となる。

package main

import "fmt"

func search(a *[]int, t int) bool {
    for _, v := range *a {
        if v == t {
            return true
        }
    }
    return false
}

func main() {
    a := []int{1, 2, 3, 4, 5, 6, 7}
    if search(&a, 7) {
        fmt.Println("ok")
    }

    if search(&a, 8) {
        fmt.Println("no")
    }
}

次回は二分探索の予定です。

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