执行二分查找的前提:这个数组必须是有序的。
1 package com.demo.sort; 2 3 public class BinarySearch { 4 /** 5 * 二分查找算法 6 * 7 * @param srcArray 有序数组 8 * @param des 查找元素 9 * @return des的数组下标,没找到返回-1 10 */ 11 12 //循环 13 public static int binarySearch(int[] srcArray, int des) { 14 int left = 0; 15 int right = srcArray.length - 1; 16 while (left <= right) { 17 int middle = (left + right) / 2; 18 if (des == srcArray[middle]) { 19 return middle; 20 } else if (des < srcArray[middle]) { 21 right = middle - 1; 22 } else { 23 left = middle + 1; 24 } 25 } 26 return -1; 27 } 28 29 //递归 30 public static int binSearch(int srcArray[], int start, int end, int key) { 31 int mid = (end - start) / 2 + start; 32 if (srcArray[mid] == key) { 33 return mid; 34 } 35 if (start >= end) { 36 return -1; 37 } else if (key > srcArray[mid]) { 38 return binSearch(srcArray, mid + 1, end, key); 39 } else if (key < srcArray[mid]) { 40 return binSearch(srcArray, start, mid - 1, key); 41 } 42 return -1; 43 } 44 45 public static void main(String[] args){ 46 int[] src = new int[] { 1, 3, 5, 7, 8, 9 }; 47 System.out.println(binarySearch(src, 9)); 48 } 49 50 }