无法在按行二分搜索中迭代二维数组中的所有行

问题描述 投票:0回答:1

为什么我的 for 循环没有迭代到二维数组中的行?

#include <iostream>
using namespace std;

//row-wise binary search.

int search2DArray(int matrix[][4], int n, int m, int key){
int start = 0, end = m-1;

    for(int i=0; i<n; i++){
    
        while(start<=end){
            int mid = (start+end)/2;
    
            if(matrix[i][mid] == key){
                cout<<"FOUND\n";
                return 0;
            }else if(matrix[i][mid] < key){ 
                start = mid + 1;
            }else{
                end = mid - 1;
            }   
        }
    
    }
    cout<<"NOT FOUND\n";
    return -1;

}

int main(){

    int matrix[4][4] = {{10,20,30,40},
                        {15,25,35,45},
                        {27,29,37,48},
                        {32,33,39,50}};
    
    search2DArray(matrix, 4, 4, 29);
    
    return 0;

}

我尝试应用 for 循环来迭代 2D 数组的所有行,但无法超过第一行,并且对于行 > 0 的任何输入始终打印 NOT FOUND。

c++ arrays loops 2d
1个回答
0
投票

当您完成一行时,您忽略了重置

start
end
,因此下一行以
start
end
开始,处于退出状态。

int search2DArray(int matrix[][4], int n, int m, int key){
//    int start = 0, end = m-1; <<-- move this line 

    for(int i=0; i<n; i++){
        int start = 0, end = m-1; // <<-- to here
        while(start<=end){
            int mid = (start+end)/2;

            if(matrix[i][mid] == key){
                cout<<"FOUND\n";
                return 0;
            }else if(matrix[i][mid] < key){
                start = mid + 1;
            }else{
                end = mid - 1;
            }
        }

    }
    cout<<"NOT FOUND\n";
    return -1;

}
© www.soinside.com 2019 - 2024. All rights reserved.