二分法查找元素 发表于 2019-04-30 | 更新于 2019-05-02 | 分类于 算法 | 评论数: | 阅读次数: 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879/** * 二分查找的前提: 数组元素必须有序. * 如果数组元素无序,那么请使用基本查找 */public class BinarySearchDemo { public static void main(String[] args) { // 定义一个数组 int[] arr = {13, 24, 57, 69, 80} ; // 调用方法 int index = binarySearch(arr , 80) ; // 输出 System.out.println("index: " + index); } /** * 二分查找 */ private static int binarySearch2(int[] arr, int value) { // 定义两个int类型的变量 int minIndex = 0 ; int maxIndex = arr.length - 1 ; while(minIndex <= maxIndex){ // 计算出中间索引 int midIndex = (minIndex + maxIndex) >>> 1 ; // 比较 if(arr[midIndex] == value){ return midIndex ; }else if(arr[midIndex] > value){ maxIndex = midIndex - 1 ; }else if(arr[midIndex] < value){ minIndex = midIndex + 1 ; } } return -1; } /** * 二分查找 */ private static int binarySearch(int[] arr, int value) { // 定义两个int类型的变量 int minIndex = 0 ; int maxIndex = arr.length - 1 ; // 计算出中间索引 int midIndex = (minIndex + maxIndex) / 2 ; while(minIndex <= maxIndex){ // 比较 if(arr[midIndex] == value){ return midIndex ; }else if(arr[midIndex] > value){ maxIndex = midIndex - 1 ; }else if(arr[midIndex] < value){ minIndex = midIndex + 1 ; } midIndex = (minIndex + maxIndex) / 2 ; } return -1; }} -------------本文结束感谢您的阅读------------- 打赏 微信支付 支付宝