设定整数数组 B[m+1][n+1]的数据在行、列方向上都按从小到大的顺序排序, 且整型变量 x 中的数据在 B 中存在。试设计一个算法,找出一对满足 B[i][j]==x 的 i,j 值。 要求比较次数不超过 m+n。
//设定整数数组 B[m+1][n+1]的数据在行、列方向上都按从小到大的顺序排序,
//且整型变量 x 中的数据在 B 中存在。试设计一个算法,找出一对满足 B[i][j]==x 的 i,j 值。 要
//求比较次数不超过 m+n。
#include <iostream>
#include <iomanip>
#include <cstdio>
using namespace std;
int m=10,n=10;
int B[11][11];
void Find(int x)
{
int c=1,r=n; // 从右上角开始找
while(B[c][r] != x) {
if(B[c][r] > x)
r--;
else
c++;
}
printf("(%d, %d)\n",c,r);
}
int main()
{
// 生成符合要求的矩阵B
for(int i=1;i<=m;i++)
B[i][0] = i;
for(int i=1;i<=m;i++) {
for(int j=1;j<=n;j++)
B[i][j] = B[i][j-1]+1;
}
cout << "矩阵B:" << endl;
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
cout.fill('0');
cout << setw(2) << B[i][j] << " ";
}
cout << endl;
}
int Count=0; //统计比较次数;
int x; // 要查找的元素x;
int sum=0; // 统计元素值为x的元素的个数
while(1) {
cout << "输出要查找的值x x∈(2,20),输入0结束:";
cin >> x;
if(!x)
break;
Find(x);
}
}