Find a number in sorted multidimentional array with binary search

后端 未结 10 903
深忆病人
深忆病人 2021-01-14 02:12

we got an increasing sorted multidimensional array for example:

int[][] mat = {{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}};

How can

相关标签:
10条回答
  • 2021-01-14 02:45

    You can do this by translating the one-dimensional index into its two-dimensional counterpart. For example, index 0 maps to 0, 0, but index 4 will map to 1, 0, and index 15 will map to 3, 3.

    This way you can use the standard binary-search algorithm, and all you have to do is to invoke the translation function when you need to look up the value at that particular index.

    The formula to translate the one-dimensional index into its two-dimensional counterpart would be:

    row = floor(index / columns);
    column = index % columns;
    

    This assumes that each array is sorted and that when flattened, the resulting array is also sorted.

    0 讨论(0)
  • 2021-01-14 02:48

    You could use the first number of each array (or the last) to find the element where your number could be present and then use binary search on that element to find if it's actually there.

    0 讨论(0)
  • 2021-01-14 02:53

    You can create an one dimensional array and use binary search .

        int[] arr = new int[]{1, 5, 6};// your converted array
        int index = Arrays.binarySearch(arr, 1);
        if (index >= 0) {
            System.out.println("found ");
        } else {
            System.out.println("not found");
        }
    
    0 讨论(0)
  • 2021-01-14 02:54

    If the multidimensional array is sorted, you could divide the binary search algorithm in two parts. First of all, you would perform the binary search to find the array inside the multidimensional one which contains the number you are looking for. And then, you perform the search inside that array.

    Hope that helps.

    0 讨论(0)
提交回复
热议问题