在一個二維數組中,每一行都按照從左到右遞增的順序排列,每一列也按照從上到下遞增的順序排列。在這樣一個序列中查找一個數
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
例如查找7,就從第一行的最左邊查找,9大于7,則9以下的也不用再查找,就從8開始,8大于7,8以下的就不用再查找,從2開始查找,2小于7,那么這一行2左邊的就不用再查找,就從4開始,4小于7,那么這一行4左邊的也不用再查找,從4下面行開始查找,代碼如下:
bool Find(int *a, int rows, int cols, int key)
{
int i = 0;
int j = cols;
while (i<rows && j >= 0)
{
if (a[i*cols + j - 1] == key)
{
return ?true;
}
else if (a[i*cols + j - 1] > key)
{
j--;
}
else
{
i++;
}
}
return false;
}
int main()
{
int a[4][4] = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 }, { 6, 8, 11, 15 } };
int ret = Find(a, 4, 4, 18);
if (ret > 0)
{
printf("yes");
}
else
{
printf("no");
}
system("pause");
return 0;
}
轉載于:https://blog.51cto.com/10810512/1774616