遍歷和二分法求解二維數組中查找問題

/**
 * Created by cuboo on 2017/4/20.
 * 問題:在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。
 * 請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。
 */
public class test {
    public static void main(String[] agrs){
        int[][] a;
        a = new int[8][8];
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                a[i][j] = i+j;
            }
        }
        System.out.println(new test().binaryFind(5,a));

    }

    /**
     * 二維數據暴力遍歷查找
     * @param target
     * @param array
     * @return
     */
    public boolean allFind(int target, int [][] array) {
        for(int i = 0;i < array.length;i++){
            for (int j = 0; j < array[i].length; j++) {
                 if (target == array[i][j]){
                     return true;
                 }
            }
        }
        return false;

    }


    /**
     * 二維數據二分法查找
     * @param target
     * @param array
     * @return
     */
    public boolean binaryFind(int target, int [][] array) {

        for(int i = 0;i < array.length;i++){
            if (binaryQuery(array[i],target)){
                 return true;
            }
        }
        return false;
    }

    /**
     * 二分法查找
     * @param target
     * @param array
     * @return
     */
    public  boolean binaryQuery(int[] array,int target){
        int length = array.length;
        int low = 0;
        int high = length - 1,middle = 0;
        while (low <= high){
            //判斷奇數
            int tem = low + high;
            if (tem%2 == 0){
                middle = tem/2;
            }else {
                middle = tem/2 + 1;
            }

            if (target == array[middle]){
                return true;
            }
            else if (target > array[middle]){
                low = middle + 1;
            }else {
                high = middle - 1;
            }
        }
        return false;
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章