Binary search in two-dimensional array

I wonder if binary search can be applied to a 2D array ?

  • What would be the conditions in the array? 2D sorting ??
  • What will be the difficulty for him?
  • How will the algorithm change the search boundary (minX, maxX, minY, maxY)?

Edit:

1D binary search supports 2 minXand pointers maxX. It selects the average index (minX+maxX)/2and compares it with the search value, if it is more than a change maxX, otherwise change minX... tominX>=maxX

Pseudocode for normal binary seacrh:

 min := 1;
  max := N; {array size: var A : array [1..N] of integer}
  repeat
    mid := min + (max - min) div 2;
    if x > A[mid] then
      min := mid + 1
    else 
      max := mid - 1;
  until (A[mid] = x) or (min > max);

thank

+3
5

O(m + n) , m = . = . .

: ( ) , , , , , .

Java :

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

, , .

+4

... , :

, 2D- . , A [i] [j] x = y = j. , , :

p1 < p2 , :

  • (x- p1) < (x- p2)
  • (x- p1) = (x- p2) (y- p1) < (y- p2)

p1 >= p2.

, 2D-, 2- 1- . ( ).

:

  • A [i] [j] > A [k] [j] , (i > k). ( )
  • A [i] [j] > A [i] [k] , (j > k). ( )

, N M . () 2D- 1D-, (T- ):

for i:=0 to N-1 do
    for j:=0 to M-1 do
        T[i*N + j]:= A[i][j];

1D . . , .

2D-, :

for i:=0 to N*M-1 do
    A[i div N][i - (i div N)*N]:= T[i];

:

x- ( ), y- ( ) .

, mid = mid + (max - min) div 2 A [mid] [0] ( x), , ( [mid]).

:

  • : log (N * M)
  • 2D-: log (N) ( ) + log (M) ( ).

, : log (N) + log (M) = log (N * M).

, , , .

, , 1-D ( ).

+2

" ",

int r = arr.length; // ROW Count
int c = arr[0].length; // Column Count
int start = 0; // Initialize with the 0
int end = r*c-1; // Last Index

while, .
while ( <= ) {

int mid = (start+end)/2;
int midX = mid/c;
int midY = mid%c;

, .

if(arr[midX][midY] == searchElement){
return true;
}

, , mid = mid + 1

if(arr[midX][midY] < searchElement){
start = mid+1;
}

, , mid = mid - 1

else{
end = mid-1;
}
+1

. , , . 1-D , . , 1-D 2-D , .

, , . :

  • , , .
  • , .
  • , .

@Bart Kiers, .

0

2D- 1D- . O(log(m * n)) mxn.

-1

Source: https://habr.com/ru/post/1779832/


All Articles