欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

二分查找程序(Java实现)

程序员文章站 2022-05-18 17:34:57
请写一个二分查找程序,判断目标数是否在数组中存在,并返回其下标(Java实现)package com.zero;public class BinarySearch { public static int[] DATAS = {2, 5, 7, 10, 22, 27, 41, 56, 99, 102}; public static void main(String[] args) { System.out.println("search(20) = " + searc...

请写一个二分查找程序,判断目标数是否在数组中存在,并返回其下标(Java实现)

package com.zero;

public class BinarySearch {

    public static int[] DATAS = {2, 5, 7, 10, 22, 27, 41, 56, 99, 102};

    public static void main(String[] args) {
        System.out.println("search(20) = " + search(20));
    }

    public static int search(int goal) {
        int size = DATAS.length;
        //定义双指针
        int low = 0, high = size - 1;
        //当找到最后或者第一个元素时,是等于号
        while (low <= high) {
            int mid = (low + high) / 2;
            if (DATAS[mid] < goal) {
                low = mid + 1;
            }
            if (DATAS[mid] == goal) {
                return mid;
            }
            if (DATAS[mid] > goal) {
                high = mid - 1;
            }
        }
        //不存在,返回-1
        return -1;
    }
}

本文地址:https://blog.csdn.net/lazybone2020/article/details/109644781

相关标签: java算法