数组的每行从左到右是递增的,每列从上到下是递增的.
从左下角开始,小于向上走,大于向右走
#include <iostream>
using namespace std;
template<class Type>
bool search(Type a[][100], Type s, int l, int c, int &x, int &y) //s为要寻找的字符,n为数组长度。x,y为返回的数组下标
{
int i = l - 1, j = 0; //从左下角开始
while (i > -1 && j < n)
{
if (s < a[i][j])
{
i--;
}
else if (s > a[i][j])
{
j++;
}
else
{
x = i;
y = j;
return true;
}
}
return false;
}
int main()
{
int a[100][100] = { 0 };
int l, c;
cin >> l >> c; //二维数组的行和列
for (int i = 0; i < l; i++)
for (int j = 0; j < c; j++)
{
cin >> a[i][j];
}
int s;
cin >> s;
int x = 0, y = 0;
if (search(a, s, c, l, x, y))
{
cout << x << " " << y;
}
else
{
cout << "不存在";
}
return 0;
}