题:在每一行从左到右递增,每一列从上到下递增,二维数组的查找重点在于从右上角开始找
#include <iostream>
using namespace std;
#define COLS 4
#define ROWS 4
bool findInPartiallySortedMatrix(int *A,int key)
{
bool f=false;
int col=COLS-1,row=0;
if(A!=NULL&&COLS>0&&ROWS>0)
{
while(row<ROWS&&col>0)
{
if(A[row*COLS+col]>key)
col--;
else if(A[row*COLS+col]<key)
row++;
else
{
f=true;
break;
}
}
}
return f;
}
int _tmain(int argc, _TCHAR* argv[])
{
int A[ROWS][COLS]={{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
int key;
cout<<"想要查找的数字是:";
cin>>key;
bool f=findInPartiallySortedMatrix(*A,key);
if(f)
cout<<"Find!"<<endl;
else
cout<<"NotFound!"<<endl;
return 0;
}