java 实现 二分 查找

Java

2017-07-06

201

0

技术:java8

运行环境:IDEA 15.2 + jdk8 + windows 10

demo功能:java实现一个二分折半查找并测试

源代码

http://git.oschina.net/youlixishi/demo-world/blob/master/src/algorithm/binary-search/src/main/java/com/demoworld/BinarySearchTest.java

public int binarySearch(int[] arr, int x) {
    if (arr == null || arr.length == 0) {
        return -1;
    }
    if (x < arr[0]) {
        return -1;
    }
    if (x > arr[arr.length - 1]) {
        return -1;
    }
    int returnIndex = -1;
    int startIndex = 0;
    int endIndex = arr.length - 1;
    int middleIndex = (startIndex + endIndex) / 2;
    while (true) {
        if (x == arr[startIndex]) {
            returnIndex = startIndex;
            break;
        }
        if (x == arr[endIndex]) {
            returnIndex = endIndex;
            break;
        }
        if (x == arr[middleIndex]) {
            returnIndex = middleIndex;
            break;
        }
        if (middleIndex == startIndex || middleIndex == endIndex) {
            break;
        }
        if (x > arr[middleIndex]) {
            startIndex = middleIndex;
        }
        if (x < arr[middleIndex]) {
            endIndex = middleIndex;
        }
        middleIndex = (startIndex + endIndex) / 2;
    }
    return returnIndex;
}

测试

源代码中包含测试用例, 目前都是测试通过的

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think