给定一个按行排序的整数矩阵结构,如何实现二分查找?
Given a matrix structure of integers that is sorted row by row, how do I implement binary search?
假设我有一个矩阵结构,它看起来像:
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?
}
}
}
如果所有元素都是一个大的排序列表,按行为主的顺序放置在数组中,那么您可以将其视为一个大数组,并使用标准的二进制搜索。
如果每一行都已排序,但行与行之间没有特定的关系,则必须独立地搜索每一行。
如果这些描述都不适合您的问题,您需要更好地解释如何填充数组的约束是什么。
相关文章:
- 如何在层次结构中实现运算符使用?
- Trie数据结构的实现
- 如何在结构中实现文件读取和创建
- 我应该使用什么样的数据结构来实现UPGMA
- 我是否需要遍历升压 rtree 的层次结构才能实现最大效率?
- 我应该如何在恒定长度的 STL 样式数据结构中实现max_size?
- 关于类的想法 参数结构给定实现
- 堆栈(数据结构)实现
- .h 文件中的客户端结构与实现结构
- C++ 在结构上实现 ORDER BY
- 什么样的数据结构可以实现并行处理
- 您将使用什么数据结构来实现字典
- 正确的数据结构,实现快速插入和快速搜索
- 从类中访问结构和实现图形的其他问题
- 手动填充顶点结构以实现对齐
- C++中的图状数据结构和实现
- 需要结构包含/实现帮助(pt 2)C++
- 需要结构包含/实现帮助(c++)
- 私有成员函数和结构以及实现文件本地的帮助程序
- 理解堆栈数据结构并实现它