给定一个按行排序的整数矩阵结构,如何实现二分查找?

Given a matrix structure of integers that is sorted row by row, how do I implement binary search?

本文关键字:结构 何实现 二分查找 实现 一个 排序 整数      更新时间:2023-10-16

假设我有一个矩阵结构,它看起来像:

1 3 4
7 8 9
11 15 18

,这个结构体作为一个二维数组传递给我,叫做"ppArr"。

所以ppArr[0][0] = 1, ppArr[0][1]=3,..., ppArr[2][2] = 18.

我正在尝试实现以下功能:

bool elementExists(int ** ppArr, int target, int rowSize, int colSize);

所以elementExist(ppArr, 9,3,3)返回true,但elementExists(ppArr, 14,3,3)返回false

我对如何解决这个问题有一个大致的想法,这里是一些伪代码:

// loop until found or no more elements left

while (true) {
   int rowMp = rowSize / 2; // computing row mid point
   int colMp = colSize / 2; // computing column mid point
 // check if midpoint value is equal to target
    if(target == ppArr[rowMp][colMp]){ 
        // found it
        return true;
    }
    else{
        // check bounds
        // if we are on the last element
        if (rowMp == rowSize-1) && (colMp == colSize =1){
            // we have reached the end of our search with no success
            return false;
        }
        // if we are on the first element
        if (rowMp == 0 && colMp == 0){
            // we have reached the start point of structure with no success
            return false;
        }

        // case 1 - target bigger than midpint
        if (target > ppArr[rowMp][colMp]){ 
             // TODO: how do I increment my rowMP and colMP here? I'm stuck
        }
        // case 2 - target smaller than midpoint
        if (target < ppArr[rowMidPointIndex][colMidPointIndex]){
            // TODO: how do i decrement my rowMP and colMP here?
        }
    }
}

如果所有元素都是一个大的排序列表,按行为主的顺序放置在数组中,那么您可以将其视为一个大数组,并使用标准的二进制搜索。

如果每一行都已排序,但行与行之间没有特定的关系,则必须独立地搜索每一行。

如果这些描述都不适合您的问题,您需要更好地解释如何填充数组的约束是什么。