package lirui.find; /** * Created by lirui on 14-8-14. */ public class BinarySearch { /** * 二分查找法要求传入的参数是有序的,且从小到大递增。 * 循环的方式实现。 * * @param list * @param key * @return */ public static int mybinarySearch(int[] list, int key) { int low = 0, high = list.length, mid; int n = list.length; while (low <= high) { mid = (low + high) / 2; if (key == list[mid]) { return mid; } if (key < list[mid]) { high = mid - 1; } else { low = mid + 1; } } return -1; } // 用递归算法实现二分查找 public static int mybinarySearchRec(int[] list, int key, int low, int high) { int mid; if (low <= high) { mid = (low + high) / 2; if (key == list[mid]) { return mid; } if (key < list[mid]) { return mybinarySearchRec(list, key, low, mid - 1); } else { return mybinarySearchRec(list, key, mid + 1, high); } } return -1; } public static void main(String[] args) { int[] list = {2, 4, 6, 7, 9, 10, 33, 500}; int result = mybinarySearch(list, 5); System.out.println(result); int result2 = mybinarySearchRec(list,5,0,7); System.out.println(result2); } }
原文:http://blog.csdn.net/u012814506/article/details/38560281