在一个每一行从左到右递增每一列从上到下递增的二维数组中查找一个整数是否存在

来源:互联网 发布:淘宝店铺号在哪里看 编辑:程序博客网 时间:2024/04/30 15:04

首先,可以从数组的右上角开始判断,试想,如果要查找的数比右上角的数要小的话,那么右上角所在的那一列都可以被排除了,当然如果等于右上角的话就直接返回了,而如果要查找的数比右上角的数要大的话,那么右上角所在的那一行都可以排除了,当判断之后所排除的那一行或者那一列不在考虑范围之内了之后,再次寻找剩下的右上角的数据,依次循环判断,直到行从0变到最大值,列从最大值变为0为止;

#include <iostream>#include <assert.h>using namespace std;bool SearchNum(int (*parr)[5], size_t row, size_t col, int num){    assert(parr);    size_t tmp_row = 0;    size_t tmp_col = col-1;    while((tmp_row < row) && (tmp_col >= 0))     {           if(parr[tmp_row][tmp_col] == num)            return true;        else if(parr[tmp_row][tmp_col] > num)            --tmp_col;        else            ++tmp_row;    }       return false;}int main(){    int arr[5][5] = {{0,  1,  2,  3},                      {5,  9, 10, 11},                     {6, 13, 16, 17},                     {7, 14, 19, 21}};    bool ret = SearchNum(arr, 4, 4, 9);  //success return true, failed return false    if(ret)        cout<<"the num is exist..."<<endl;    else        cout<<"the num is not exist..."<<endl;    return 0;}


1 0
原创粉丝点击