java-二分查找

二分查找也叫折半查找,前提是数组是有序数组,下面来分析原理。

如果一个数组:

int arr[] = {1,2,3,4,5,6};

要查找1所在的索引值,那么先确定最大索引值maxIndex和最小索引值minIndex,然后计算出中间的索引值和midIndex

int maxIndex = arr.length-1;
int minIndex = 0;
int midIndex = (minIndex + maxIndex)/2;

根据中间的索引值找到中间的元素和1,比较如下通过比较midValue和1的值,如果midValue比1大,那么就在数组arr[minIndex]到arr[midIndex-1]里面继续和进行上面的比较结果,如果midValue比1小,那么就在数组arr[minIndex+1]到arr[maxIndex]里面继续进行上面的比较,如果找到,则直接返回索引,如果没有找到一直到minIndex > maxIndex结束,说明没找到返回-1.

while (arr[midIndex] != value) {
     if (arr[midIndex] > value) {
         maxIndex = midIndex - 1;
     } else {
         minIndex = midIndex + 1;
     }
     if (minIndex > maxIndex) {
         return -1;
     }
     midIndex = (minIndex + maxIndex) / 2;
 }
 return midIndex;

如果所示:

可以如果在1.2.3.4.5.6 里面用二分查找找1需要 3次查找。

二分查找的时间复杂度为: log2n
参考:http://blog.csdn.net/frances_han/article/details/6458067

完整代码:

public class BinarySearch {
    public static void main(String[] args) throws Exception {
        int arr[] = {1, 2, 3, 4, 5, 6};
        int index = getIndex(arr, 1);
        System.out.println("index:" + index);
        int index = getIndex(arr, 7);
        System.out.println("index:" + index);
    }

    private static int getIndex(int[] arr, int value) {
        int minIndex = 0;
        int maxIndex = arr.length - 1;
        int midIndex = (minIndex + maxIndex) / 2;

        while (arr[midIndex] != value) {
            if (arr[midIndex] > value) {
                maxIndex = midIndex - 1;
            } else {
                minIndex = midIndex + 1;
            }
            if (minIndex > maxIndex) {
                return -1;
            }
            midIndex = (minIndex + maxIndex) / 2;
        }
        return midIndex;
    }
}

你可能感兴趣的:(二分查找,折半查找,java查找)