当前位置:   article > 正文

Java二分查找法代码_java二分法查找代码

java二分法查找代码
//主方法
import domain.binartSearchForIndex;

public class MyBinarySearchDemo {
    public static void main(String[] args) {
        //定义静态整数数组
        int[] arr = {11,22,33,44,55};
        //创建要查找的数字
        int number = 33;
        //类名.方法名 传入数组和整数参数,并创建变量x接收返回回来的整数
        int x = binartSearchForIndex.binartSearchForIndex(arr,number);
        //打印该数字在数组中的位置
        System.out.println(x);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
//二分查找方法体
public class binartSearchForIndex {
    /*
        二分查找法
     */
    //传入一个数组参数,和要查找的值
    public static int binartSearchForIndex(int[] arr, int number) {
        //定义查找范围
        int min = 0;
        int max = arr.length - 1;
        //while判断
        while (min <= max) {
            //计算出中间的位置
            int mid = (min + max) / 2;
            //mid指向的元素 > number
            if (arr[mid] > number) {
                max = mid - 1;
            } else if (arr[mid] < number) {
                //mid指向的元素 < number
                //表示要查找的元素在右边
                min = mid + 1;
            } else {
                //mid指向的元素 = number
                return mid;
            }
        }
        //如果min大于了max 就表示元素不存在,返回 -1
        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
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/977664
推荐阅读
相关标签
  

闽ICP备14008679号