Topic
In a two-dimensional array, each row is ordered in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Complete a function, enter a two-dimensional array and an integer to determine if the array contains the integer.
Problem analysis
We should start with specific problems and find out the common laws by analyzing simple and concrete examples.
Now let's assume we're going from a two-dimensional array
1 7 14 21
3 8 15 22
5 9 16 23
7 17 23 24
Retrieves whether the number 7 exists.
The array is retrieved in order of precedence from the top right of the column.
1. When retrieving 17, the fourth column can be excluded because 21 is greater than 17.
2. When retrieving 14, since 14 is less than 17, it is possible to remove the first line, which is equivalent to updating the line number and the column number and then re-executing it. The remaining
3 8 15
5 9 16
7 17 23
3. When retrieving 15, since 15 is less than 17, it is possible to remove the first line, leaving only
5 9 16
7 17 23
4. When retrieving 16, since 16 is less than 17, it is possible to remove the first line, leaving only
7 17 23
5. When retrieving 23, because 23 is greater than 17, the third column can be excluded, leaving only
7 17
6. Retrieved 17, returned.
The code is implemented as follows:
#include <stdio.h>#defineM 4#defineN 4intFindnumber (intArray[m][n],intRowsintColumnsintNumber ) { if(Array!=null && rows>0&& columns>0) { intcol=columns-1, row=0; while(col>=0&& row<rows) { if(array[row][col]>Number ) {Col--; Continue; } Else if(array[row][col]<Number ) {Row++; Continue; } Else return 1; } return 0; } Else return 0;}intMainvoid){ inta[m][n]={ {1,7, -, +},{3,8, the, A},{5,9, -, at},{7, -, at, -} }; intnum; printf ("the array to test is: \ n"); for(intI=0; i<m;i++) { for(intj=0; j<n;j++) {printf ("%d", A[i][j]); } printf ("\ n"); } printf ("Please enter the number you want to find:"); while(SCANF ("%d",&num)) { if(Findnumber (a,m,n,num)) printf ("the number exists \ n"); Elseprintf ("The number does not exist \ n"); printf ("Please enter the number you want to find:"); } return 0;}
The results are as follows:
$./myfindnumberintwoarrays.exe
The array to be tested is:
1 7 14 21
3 8 15 22
5 9 16 23
7 17 23 24
Please enter the number to find: 17
The number exists
Please enter the number to find: 23
The number exists
Please enter the number to find: 22
The number exists
Please enter the number to find: 10
The number does not exist
Please enter the number to find: 6
The number does not exist
Please enter the number you want to find:
Finding in a two-dimensional array