An instance of a lookup in a two dimensional array in the C language
- 2020-05-26 09:54:05
- OfStack
An instance of a lookup in a 2-dimensional array in the C language
In a 2-d array, each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Please complete a function, enter such a 2 - dimensional array and an integer, determine whether the array contains the integer
Description: the lower part and the right part of a number are larger areas than itself, while the left part and the upper part are smaller areas than itself. Select the number in the upper right corner for comparison. When the number is greater than the specified number, omit the column; when the number is less than the specified number, omit the line; when equal, find
C language implementation:
#include<stdio.h>
#include<stdlib.h>
typedef unsigned int boolean;
#define MAX 4
#define TRUE 1
#define FALSE -1
void showAry(int ary[MAX][MAX]);
boolean find(int ary[MAX][MAX], int rows, int cols, int number);
void showAry(int ary[MAX][MAX]) {
int i = 0, j = 0;
for(; i < MAX; i++) {
j = 0;
for(; j < MAX; j++) {
printf("%d ", ary[i][j]);
}
}
}
boolean find(int ary[MAX][MAX], int rows, int cols, int number) {
int i = 0,
j = cols - 1,
n = 0;
boolean result = FALSE;
if(ary == NULL || rows <= 0 || cols <= 0) {
return result;
}
while(i < rows && j >= 0) {
n = ary[i][j];
if(number == n) {
printf("\nary[%d, %d] = %d\n", i, j, n);
result = TRUE;
break;
}else if(number < n) {
j -= 1;
}else if(number > n) {
i += 1;
}
}
return result;
}
//1 2 8 9 2 4 9 12 4 7 10 13 6 8 11 15
int main() {
int ary[MAX][MAX];
int i = 0, j = 0;
for(; i < MAX; i++) {
j = 0;
for(; j < MAX; j++) {
scanf("%d", &ary[i][j]);
}
}
showAry(ary);
find(ary, MAX, MAX, 7);
}
The above is to explain C language 2 dimensional array in the search of the example, hope to help the same type of problems need friends, thank you for reading, hope to help you, thank you for the support of this site!