二分查找

java

package coder.zte.excecize;
import java.util.Arrays;

public class BinarySearch{
    public static int rank(int key,int[] a) {
        
        int lo=0;
        int hi=a.length-1;
        while(lo<hi) {
            int mid=lo+(hi-lo)/2;
            if(a[mid]<key) lo=mid+1;
            else if(a[mid]>key) hi=mid-1;
            else return mid;
            
        }
        return -1;
    }
    
    public static void  main(String[] args) {
        
        int[]aaa=new int[5];
        for(int a=0;a<aaa.length;a++) {
            aaa[a]=a+1;
        }
        int re=rank(3,aaa);
        
        System.out.println();
        System.out.print(re);
        
    }
}
posted @ 2020-12-25 16:17  梅谷暴君  阅读(66)  评论(0编辑  收藏  举报