码迷,mamicode.com
首页 > 编程语言 > 详细

java二分查找

时间:2019-03-27 20:58:40      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:ati   sort   div   sea   search   ret   imp   void   length   

java二分查找

import java.util.Arrays;

public class TestBianarySearch3 {
    public static void main(String[] args) {
        int [] arr = {23,34,45,65,26,76,86,45,765,43};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        System.out.println(BianarySearchResult(arr,45)+1);
        
    }
    public static int BianarySearchResult(int[] arr,int result) {
        int low = 0;
        int high = arr.length-1;
        while(low<=high) {
            int mid = (low+high)/2;
            if( arr[mid] == result) {
                return mid;
            }
            if(result<arr[mid]) {
                high = mid-1;
            }
            if(result>arr[mid]) {
                low = high+1;
            }                
        }
        return -1;
    }
    
}

 

java二分查找

标签:ati   sort   div   sea   search   ret   imp   void   length   

原文地址:https://www.cnblogs.com/OldFour/p/10610596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!