/*
***数字包含在数组中(为数组中的最大值或最小值或介于最大与最小之间)
***数字不包含在数组中(大于最大值或小于最小值或介于最大与最小之间但不包含)
***输入数组为空指针
*/
void test(char* testName, int* matrix, int rows, int columns, int number, bool expected){
if(testName != nullptr){
printf("%s begins: ", testName);
}
bool result = find(matrix, rows, columns, number);
if(result == expected){
printf("Passed.\n");
}
else{
printf("Failed.\n");
}
}
/*******数组********/
// 1 2 8 9
// 2 4 9 12
// 4 7 10 13
// 6 8 11 15
int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
//要查找的数在数组中
void test1(){
test("test1", (int*)matrix, 4, 4, 7, true);
}
//要查找的数不在数组中
void test2(){
test("test2", (int*)matrix, 4, 4, 5, false);
}
//要查找的数是数组中最小的数字
void test3(){
test("test3", (int*)matrix, 4, 4, 1, true);
}
//要查找的数是数组中的最大的数字
void test4(){
test("test4", (int*)matrix, 4, 4, 15, true);
}
//要查找的数比数组中最小的数字还小
void test5(){
test("test5", (int*)matrix, 4, 4, 0, false);
}
//要查找的数比数组中最大的数字还大
void test6(){
test("test6", (int*)matrix, 4, 4, 16, false);
}
//鲁棒性测试,输入空指针
void test7(){
test("test7", nullptr, 0, 0, 16, false);
}
#include <cstdio>
bool find(int* matrix, int rows, int columns, int number){
bool found = false;
if(matrix != nullptr && rows > 0 && columns > 0){
int row = 0;
int column = columns - 1;
while(row < rows && column >= 0){
if(matrix[row*columns+column] == number){
found = true;
break;
}
else if(matrix[row*columns+column] > number){
column--;
}
else{
row++;
}
}
}
return found;
}
int main(){
test1();
test2();
test3();
test4();
test5();
test6();
test7();
return 0;
}
原文:https://www.cnblogs.com/tangliang39/p/11694332.html