美文网首页
二分法查找

二分法查找

作者: Frank_8942 | 来源:发表于2019-06-04 13:04 被阅读0次
    # 二分法查找的前提是, 数组内的数据是有序的
    
    public class Three {
        public static void main(String[] args) {
    
            int[] arr = new int[]{1,2,3,4,5,6,7};
            int i = find(arr,6);
            System.out.println(i);
            System.out.println(i + "   " + arr[i]);
    
        }
    
        private static int find(int[] arr, int element) {
            int left = 0;
            int right = arr.length-1;
            int res = -1;   //要返回的结果值
            while (left <= right){
                int mid = (left + right)/2;
                if (arr[mid] < element){
                    left = mid + 1;
                }else if (arr[mid] > element){
                    right = mid - 1;
                }else {
                    res = mid;
                    break;
                }
            }
            return res;
        }
        
    }
    
    

    相关文章

      网友评论

          本文标题:二分法查找

          本文链接:https://www.haomeiwen.com/subject/ocbyjqtx.html