当前位置:   article > 正文

二分查找 java代码实现_二分查找代码实现java

二分查找代码实现java

二分查找java代码

package csdn.dreamzuora.query;

/**
 * Title: 二分查找
 * Description:
 * 时间复杂度:log2N
 * @version 1.0
 * @author: weijie
 * @date: 2020/10/16 13:52
 */
public class BinarySearch implements Search {

    int[] array;
    public BinarySearch(int[] array) {
        this.array = array;
    }

    @Override
    public int search(int data) {
        int startIndex = 0;
        int endIndex = array.length - 1;
        int midIndex = startIndex + (endIndex - startIndex) / 2;
        while (midIndex >= startIndex && midIndex <= endIndex){
            if (array[midIndex] == data){
                return midIndex;
            }
            if (data > array[midIndex]){
                startIndex = midIndex + 1;
            }else {
                endIndex = midIndex - 1;
            }
            midIndex = startIndex + (endIndex - startIndex) / 2;
        }
        return -1;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

单元测试

package csdn.dreamzuora.query;

import org.junit.Test;
import org.junit.jupiter.api.Assertions;

import static org.junit.Assert.*;

/**
 * Title:
 * Description:
 *
 * @version 1.0
 * @author: weijie
 * @date: 2020/10/16 14:00
 */
public class BinarySearchTest {

    @Test
    public void search() {
        int[] array = new int[10];
        for (int i = 0; i < 10; i++){
            array[i] = i;
        }
        BinarySearch binarySearch = new BinarySearch(array);
        Assertions.assertEquals(3, binarySearch.search(3));
        Assertions.assertEquals(8, binarySearch.search(8));
        Assertions.assertEquals(0, binarySearch.search(0));
        Assertions.assertEquals(9, binarySearch.search(9));
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/977765
推荐阅读
相关标签
  

闽ICP备14008679号