zoukankan      html  css  js  c++  java
  • 基础算法5——二分查找

    View Code
     1 import java.util.*;
     2 
     3 public class BinarySearch {
     4 
     5     public static void main(String[] args) {
     6         ArrayList<Integer> a = new ArrayList<Integer>();
     7         addIntegerInSequence(a, 1, 10);
     8         print(a);
     9         int pos = binarySearch(a, 10);
    10         if (pos != -1) {
    11             System.out.print("Element found: " + pos);
    12         } else {
    13             System.out.print("Element not found");
    14         }
    15     }
    16 
    17     /**
    18      * 二分查找法
    19      * 
    20      * @param a
    21      * @param value
    22      *            待查找元素
    23      * @return
    24      */
    25     public static int binarySearch(ArrayList<Integer> a, int value) {
    26         int size = a.size();
    27         int low = 0, high = size - 1;
    28         int mid;
    29         while (low <= high) {
    30             mid = (low + high) / 2;
    31             if (a.get(mid) < value) {
    32                 low = low + 1;
    33             } else if (a.get(mid) > value) {
    34                 high = high - 1;
    35             } else {
    36                 return mid;
    37             }
    38         }
    39         return -1;
    40     }
    41 
    42     /**
    43      * 填充顺序元素到数组
    44      * 
    45      * @param a
    46      * @param begin
    47      *            开始元素
    48      * @param size
    49      *            大小
    50      */
    51     public static void addIntegerInSequence(ArrayList<Integer> a, int begin,
    52             int size) {
    53         for (int i = begin; i < begin + size; i++) {
    54             a.add(i);
    55         }
    56     }
    57 
    58     /**
    59      * 打印数组
    60      * 
    61      * @param a
    62      */
    63     public static void print(ArrayList<Integer> a) {
    64         Iterator<Integer> i = a.iterator();
    65         while (i.hasNext()) {
    66             System.out.print(i.next() + " ");
    67         }
    68         System.out.println("");
    69     }
    70 
    71 }
  • 相关阅读:
    Ubuntu16.04下搭建LAMP环境
    关于下载SAE日志签名认证的方法——PHP版
    时隔这么长时间,又回来写博客了
    转战网站后台与python
    学习之路
    周末随笔
    Shell基础-环境变量配置文件
    关于骑行
    MYSQL 8.0 linux安装步骤
    一个golang项目笔记 (二) 动态加载库
  • 原文地址:https://www.cnblogs.com/perfy/p/3069202.html
Copyright © 2011-2022 走看看