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 }