LoginSignup
0
1

More than 3 years have passed since last update.

バイナリサーチ 二分検索法

Last updated at Posted at 2019-08-31

バイナリサーチ 二分検索法

範囲を半分に絞りながら探していく検索法

メリット

検索速度が速い

デメリット

データをあらかじめ整列しておく必要がある

BinarySerch.java

class BinarySerch{
  public static void main(String[] args){
   //検索するソート済の配列
   int a[] = {1,3,6,8,10};
   //検索する値
   int serchValue = 3;
   //見つかったデータの配列番号 初期値はエラー値(-1)
   int find = -1;

   //検索する左端、右端の番号
   int left = 0;
   int right = a.length-1;
   //調べる左端と右端にデータがある時は繰り返す
   while(left <= right){
     //左右の真ん中の番号を調べる位置に指定
     int middle = (int)((left + right)/2);
     //調べる位置の値と、探す位置を比較して
     if(a[middle] == serchValue){
        //同じなら、その番号を保存して繰り返しの終了
        find = middle;
        break;
    }else if (a[middle] < serchValue){
    //探す値より小さければ左端を移動
     left = middle + 1;
    }else {
    //探す値より大きければ右端を移動
    right = middle - 1;
    }
  }
  //検索結果の表示
  System.out.println("検索結果:" + find);
 }
}

参考書籍
楽しく学ぶアルゴリズムとプログラミングの図鑑

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