二分查找


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int arr [] = {12,25,36,59,78,96,125};
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            int input = sc.nextInt();
            System.out.println(array(arr,input));
        }       
    }   
    public static int array(int[]arr,int n) {

        int left = 0;
        int right = arr.length-1;

        while (left<=right) {
            int mid=(left+right)/2;
            if(arr[mid]>n) right=mid-1;
            else if(arr[mid]left=mid+1;
            else return mid;
        }
        return -1;
    }
}

你可能感兴趣的:(java,java)