黑马程序员技术交流社区

标题: 如何用二分法查找一个数再数组中的索引值? [打印本页]

作者: WilliCicci    时间: 2015-7-24 00:01
标题: 如何用二分法查找一个数再数组中的索引值?
//用二分法查找一个数再数组中的索引值,前提数组必须是有序的
public static void main(String[] args) {
                int []arr = { 18, 37, 54, 76, 92};
                int midIndex= getIndex(arr,76);
                System.out.println(midIndex);
        }
public static int getIndex(int []arr,int value){
                int maxIndex =arr.length -1 ;
                int minIndex = 0;
                int midIndex = (maxIndex+minIndex)/2 ;
                while(arr[midIndex]!=value){                   
                        if (arr[midIndex]>value) {
                                maxIndex= midIndex -1;
                        }else if (arr[midIndex]<value) {
                                minIndex =midIndex+1;
                        }
                        if (minIndex>maxIndex) {
                                return -1;
                        }
                        midIndex= (maxIndex+minIndex)/2 ;
                }
                return midIndex;
        }
------------------------------------
作者: hejin67410    时间: 2015-9-17 18:01
谢谢分享




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2