1. 程式人生 > >二分法查詢(詳解)

二分法查詢(詳解)

一共三種方案

package com.***.test;

public class BinarySearch1 {
    /**
     * 相同數時返回右邊查到的數
     */
    public static int binarySearchRight(int [] arr,int target){
        int low=0;
        int high=arr.length;
        while (low < high){
            int mid=(low+high)/2;
            if(target < arr[mid])
                high--;
            else
low++; } if(arr[high-1]==target) return high-1; else return -1; } /** * 相同數時返回左邊查到的數 */ public static int binarySearchLeft(int [] arr,int target){ int low=0; int high=arr.length; while (low < high){ int
mid=(low+high)/2; if(target <= arr[mid]) high--; else low++; } if(arr[high]==target) return high; else return -1; } /** *找的直接返回 */ public static int binarySearch(int [] arr,int
target){ int low=0; int high=arr.length; while (low < high){ int mid=(low+high)/2; if(target == arr[mid]) return mid; else if (target <arr[mid]) high--; else low++; } return -1; } public static void main(String[] args) { int [] arr={1,2,2,5,5,8,9,12}; System.out.println(binarySearchRight(arr,10)); System.out.println(binarySearchLeft(arr,10)); System.out.println(binarySearch(arr,10)); } }