题目:在二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
例如:
输入二维数组:
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
- 查找数字7,返回true;
- 查找数字5,返回false;
#include<stdio.h>
#define rows 4
#define columns 4
#define true 1
#define false 0
//核心功能函数
int find(int *a, int rs, int cs, int number) {
if ((a == NULL) || (rs < 0) || (cs < 0))
return false;
int row = 0;
int col = cs - 1;
while ((row < rs) && (col >= 0)) {
if (a[row * cs + col] == number) {
return true;
}
else if (a[row * cs + col] > number) {
col--;
}
else
row++;
}
return false;
}
//查找数字7
void test1() {
int a[rows * columns] = {1,2,8,9,2,4,9,12,4,7,10,13,6,8,11,15};
int count = find(a, rows, columns, 7);
if (count == 0)
printf("not find!\n");
else
printf("sucess!\n");
}
//查找数字5
void test2() {
int a[rows * columns] = { 1,2,8,9,2,4,9,12,4,7,10,13,6,8,11,15 };
int count = find(a, rows, columns, 5);
if (count == 0)
printf("not find!\n");
else
printf("sucess!\n");
}
//指针指向空
void test3() {
int a[rows * columns];
int count = find(NULL, rows, columns, 5);
if (count == 0)
printf("not find!\n");
else
printf("sucess!\n");
}
int main() {
test1();
test2();
test3();
return 0;
}
运行结果: