Binary Search in 2D Array

后端 未结 8 1101
南笙
南笙 2021-02-09 17:14

I wonder, can binary search be applied on a 2D array?

  • What would the conditions on the array be? Sorted on 2D??
8条回答
  •  遥遥无期
    2021-02-09 17:24

    I solved it in a simple way in O(m + n) time complexity, where m = no. of rows and n = no. of columns.

    The algorithm is simple: I started from top right corner (we can also start from bottom left corner) and move left if current element is greater than the value to be searched and bottom if current element is smaller than the value to be searched.

    The java code is like:

    public static int[] linearSearch(int[][] a, int value) {
        int i = 0, j = a[0].length - 1; // start from top right corner
    
        while (i < a.length && j >= 0) {
            if (a[i][j] == value) {
                return new int[]{i, j};
            } else if (a[i][j] > value) {
                j--; // move left
            } else {
                i++; // move down
            }
        }
        // element not found
        return new int[]{-1, -1};
    
    }
    

    Gist

    You can further reduce the time complexity by using a method called Improved Binary Partition.

提交回复
热议问题