二分查找法

/**
* 2分查找法
* @author Administrator
*
*/
public class BinarySearch {

// int binarySearch(int[] a, int value){
//        int low = 0;
//        int high = a.length-1;
//       
//        while(low <= high){
//             int   mid = (low+high)/2; //**
//                if (a[mid] == value)
//                        return mid;
//                else if (a[mid] > value)
//                        high = mid-1;
//                else
//                        low = mid +1;
//        }
//        return -1;
//}
  /**
     * * 二分查找算法 * *
     * 
     * @param srcArray
     *            有序数组 *
     * @param des
     *            查找元素 *
     * @return des的数组下标,没找到返回-1
     */  
   public static int binarySearch(int[] srcArray, int des){  
     
        int low = 0;  
        int high = srcArray.length-1;  
        while(low <= high) {  
            int middle = (low + high)/2;  
            if(des == srcArray[middle]) {  
                return middle;  
            }else if(des <srcArray[middle]) {  
                high = middle - 1;  
            }else {  
                low = middle + 1;  
            } 
        } 
        return -1; 
   } 
/**
* @param args
*/
public static void main(String[] args) {
SelectSort selectSort=new SelectSort();
BinarySearch binarySearch=new BinarySearch();

int[] a={3,2,6,9,7,1,4,5};
selectSort.selectSort(a);
int value=binarySearch.binarySearch(a,7);
System.out.println(value);


}

}

你可能感兴趣的:(二分查找法)