zoukankan      html  css  js  c++  java
  • Java-二分查找算法

    package com.lym.binarySearch;
    
    import java.util.Arrays;
    
    /**
     * 二分查找
     * 
     * @author Administrator
     * 
     */
    public class BinarySearchDemo {
    
    	public static void main(String[] args) {
    		int[] number = { 4, 2, 66, 12, 88, 95, 63, 1 };
    		Arrays.sort(number);// 先对数组排序,然后再进行二分查找
    		int index = binarySearch(number, 63);//parameter(int[],key)
    		System.out.println(index);
    	}
    
    	//二分查找
    	public static int binarySearch(int[] a, int n) {
    		rangeCheck(a.length,0,a.length-1);
    		return binarySearch0(a, 0, a.length, n);
    	}
    
    	//异常检测
    	private static void rangeCheck(int length, int fromIndex, int toIndex) {
    		if (fromIndex > toIndex) {
                throw new IllegalArgumentException(
                    "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
            }
            if (fromIndex < 0) {
                throw new ArrayIndexOutOfBoundsException(fromIndex);
            }
            if (toIndex > length) {
                throw new ArrayIndexOutOfBoundsException(toIndex);
            }
    	}
    	
    	//二分查找核心算法
    	private static int binarySearch0(int[] a, int fromIndex, int toIndex, int n) {
    		int low = fromIndex;
    		int high = toIndex - 1;
    
    		while (low <= high) {
    			int mid = (low + high) >>> 1;// middle index    采用移位运算符可以提高性能
    			int midVal = a[mid];// middle value
    
    			if (midVal > n)
    				high = mid - 1;
    			else if (midVal < n)
    				low = mid + 1;
    			else
    				return mid;//key found
    		}
    		return -(low + 1);// key no found
    	}
    
    }
    

  • 相关阅读:
    提高PHP程序运行效率的方法
    必须知道的sql编写技巧。多条件查询不拼接字符串·的写法
    数据库SQL优化大总结之 百万级数据库优化方案
    编程一开始就应该养成的好习惯
    php图像处理
    jqurey 简单的,我也简单
    菜单上下级 (全国地区)
    think php v5.0
    正则表达式
    有感赠朵朵
  • 原文地址:https://www.cnblogs.com/liuyanmin/p/5146532.html
Copyright © 2011-2022 走看看