简体   繁体   English

在二维数组上进行二进制搜索

[英]Binary Search on a 2D array

I have a 2D array which is fully sorted. 我有一个完全排序的2D数组。 The arrays below are examples 下面的数组是示例

    1  2  3  
    5  6  7  
    9 10 11 

and

    1  2  3  4  5
    6  7  8  9  10

I would like to use binary search on these array. 我想在这些数组上使用二进制搜索。 Let rows be the number of rows and cols be the number of columns rows为行数, cols为列数

Initially start = 0 and end = rows * cols -1 最初start = 0end = rows * cols -1

In the 3 X 3 array above, midpoint works out to be four [9 elements]. 在上面的3 X 3数组中,中点算出为四个[9个元素]。 Now how do I find out the corresponding row and column with the midpoint ? 现在如何找出带有中点的相应行和列? Is there any standard formula for that ? 有任何标准公式吗?

The formula is pretty simple: 公式很简单:

row = number/cols_per_row;
col = number%cols_per_row;

Let size = rows * cols size = rows * cols

mid = size // 2 (integer division) mid = size // 2 (整数除法)

row = mid // cols

col = mid % cols (rest for integer division) col = mid % cols (其余为整数除法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM