令A[low···high]为元素按照升序排列的非空数组,A[mid]为中间元素,假定x>A[mid],注意到如果x在A中,则它必定是在A[mid + 1],A[mid + 2]····A[high]当中的一个,接下来只需要在A[mid+1····high]中搜索x,换句话说,A[low····mid]中的项目在后续的比较中被丢弃掉了。因为根据前面的假定,A按照升序排列,这意味着x不会在A[low·····mid]这半部分数组当中。类似的,如果x < A[mid],只需在A[low····mid-1]中搜索x。由于重复进行二等分,所以就称为了二分搜索。
package chapter1;
public class BinarySearchTest {
public static void main(String[] args) {
int[] arr = { 1, 3, 5, 7, 9, 10, 12, 14, 16, 18, 20 };
System.out.println(binarySearch(arr, 14));
System.out.println(binarySearch(arr, 19));
}
/**
* 二分查找,数组有序,每次将有序的数组折半,查找元素。
*
* 如果待查元素在数组中,返回待查元素在数组中的位置,否则返回-1
*
* @param array
* @param searchElement
* @return
*/
public static int binarySearch(int[] array, int searchElement) {
int low = 0; // 数组最低位指针
int high = array.length; // 数组最高位指针
while (low <= high) { // 数组最低位指针 < 数组最高位指针
int mid = (low + high) / 2;
int x = array[mid];
if (x < searchElement) { // 数组中间位置的元素小于待查找元素
low = mid + 1; // 修改低位指针为mid+1
} else if (x > searchElement) {// 数组中间位置的元素大于待查找元素
high = mid - 1; // 修改高指针为mid-1
} else {
return mid;
}
}
return -1;
}
}