简体   繁体   中英

Best Time Complexity for Sorted 2D Array Search in Java

So I have the following code to search a sorted 2D array for a target number, but I am not sure if this is the best time complexity as in terms of Big-Oh, I read that there is a way to do in O(N), but I am not sure if my algorithm is efficient enough.

public class Search2DArray {

public static int search(int[][] arrayA, int number, int target) {
    int i = 0;
    int j = number - 1;
    while (i < number && j >= 0) {
        if (arrayA[i][j] == target) {
            System.out.printf("\n Found at %d, %d", i, j);
            return 1;
        }
        if (arrayA[i][j] > target) {
            j--;
        } else {
            i++;
        }
    }

    System.out.printf("\n Element not found");
    return 0;
}

public static void main(String[] args) {
    int arrayA[][] = {{1, 2, 3, 4}, 
                   {5, 6, 7, 8}, 
                   {9, 10, 11, 12}};
    search(arrayA, 3, 11);
}
}

好吧,如果对2D数组进行了排序,则可以简单地减少行以选择并在您认为包含目标数的行上进行二进制搜索,这样可以降低复杂度,甚至更好的是按LOG顺序排列

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM