LoginSignup
3
7

More than 5 years have passed since last update.

なっとく!アルゴリズム二分探索(p9)をSwiftで書く

Last updated at Posted at 2019-03-10

はじめに

なっとく!アルゴリズムの理解を深めるために、慣れているSwiftで書いてみた時のメモ

import Foundation

//第一引数とある配列を渡す
//第二引数、その配列内に特定の数字が入っていたら、その場所を返すようにする
func binarySearch(list:[Int],item:Int) {
    var low = 0
    var high = list.count - 1 

    //取り出した配列の中見を比較して、同じあたいになるまでループする
    //初回 0 < 4
    //2 0 < 1
    while (low < high) {
        print("low",low)
        print("high",high)

        //真ん中を取り出す
        let mid = Int(ceil(Double(low + high) / 2))
        //値をとりだす
        let value = list[mid]

        //とりだした値が、探したい値よりおおきいかちいさいかをしらべる
        if value == item {
            print("正解")
            return print(mid)
        } else if value < item {
            low = mid + 1
        } else {
            high = mid - 1
        }
    }
    return print("当てはまるものはない")

}

let my_list = [1,3,5,7,9]

print(binarySearch(list:my_list,item:9))

paizaでも動かしたのでメモ

Int(ceil(Double(low + high) / 2))でつまったのでメモ

本はpythonで書かれていて
pythonの//の表現をうまくSwiftで表現できなくて苦戦したのをメモした

mid = (low + high) // 2

3
7
1

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