Binary Search in 2D Array

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

    No, it is not possible to apply a binary search on a 2D array.

    Requirements for a binary search:

    Requirement 1: Items are sorted

    In a 1D array it is clear what that means. But what does that exactly mean for a 2D array?

    Requirement 2: 2 directions

    A binary search requires that when ever you pick an item in it, you can go into 2 directions from there.

    Because of the sorting, whenever you pick an item, the item supplies enough information to know in which of the 2 direction you need to continue your search. That allows to split the search scope in 2 parts and that's why we call it binary.

    If you pick an item in a 2D array, there are 4 possible directions (or even more: you could move diagonally as well). Even if all items are sorted in someway the information in one item can't tell you which direction you have to go and how to split the array based on that.

    A binary search will be possible only if you can convert the 2D array into a sorted 1D array. If a function can be defined that combines the indexes x and y into an index i for a sorted virtual 1D array containing all items in the 2D array and x and y can be calculated back from i, then you can use a binary search on that virtual 1D array. And that function depends on how the items in the 2D array are sorted. But that means you are doing a binary search on a 1D array not on a 2D array!

提交回复
热议问题