Binary Search in 2D Array

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

    If your array is sorted by increasing values, then, do a binary search on the array A[i][0] by varying i, then a binary search on A[i*][j] by varying j, where i* is the row containing the desired value.

    Finding i* would be done by checking whether the desired value lies between A[i*][0] and A[i*][m] if A[i*][0] < x on an increasing 2d array (each given line's elements are bigger than the previous').

    The complexity should be log(n)+log(m) = log(nm).

提交回复
热议问题