Binary Search in 2D Array

后端 未结 8 1098
南笙
南笙 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:40

    You can transform 2D array into 1D array and do the binary search here. Complexity is O(log(m * n)) for mxn array.

    0 讨论(0)
  • 2021-02-09 17:44

    Binary Search works in the divide and conquer way,

    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
    

    We will keep iterating the while loop, each time we updating the start and end index as per requirements..
    while(start <= end){

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

    If the current value is equals to the search element then we just have to print and return it.

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

    If the current value is smaller then the search element then we just have to update the mid value by mid = mid + 1

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

    If the current value is grater than the search element then we just have to update the mid value by mid = mid - 1

    else{
    end = mid-1;
    }
    
    0 讨论(0)
提交回复
热议问题