下面是一个实现二分查找的 Java 代码示例:

public class BinarySearch {
    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            
            if (arr[mid] == target) {
                return mid;
            }
            
            if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        
        return -1;
    }
    
    public static void main(String[] args) {
        int[] arr = {2, 4, 6, 8, 10};
        int target = 6;
        
        int result = binarySearch(arr, target);
        
        if (result == -1) {
            System.out.println('Element not found');
        } else {
            System.out.println('Element found at index ' + result);
        }
    }
}

该代码中的 binarySearch 方法接收一个已排序的整数数组和一个目标值作为参数,然后使用二分查找算法在数组中查找目标值。返回目标值在数组中的索引,如果目标值不存在则返回 -1。

main 方法中,我们创建了一个整数数组 arr 和一个目标值 target,然后调用 binarySearch 方法进行查找。最后根据返回的索引结果输出相应的信息。

Java 二分查找算法实现代码示例

原文地址: http://www.cveoy.top/t/topic/paZj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录