Search Ideas:
First, select the number in the upper-right corner of the array.
(1) If the number is equal to the number to be searched, the query process ends;
(2) If the number is greater than the number to be searched, remove the column where the number is located;
(3) If the number is smaller than the number to be searched, remove the row where the number is located.
That is to say, if the number to be searched is not in the upper-right corner of the array, a row or column is removed from the search range of the array each time, so that each step can narrow the search range, until the number to be searched is found or the search range is null.
Note: Of course, you can also search from the lower left corner. The truth is the same; but you cannot search from the upper left or lower right corner.
The preceding process is shown in:
C ++ code:
<SPAN style = "FONT-SIZE: 18px"> # include "stdafx. h "# include <assert. h> # include <iostream> using namespace std; // search for nFindNum in the two-dimensional array p_nArray in the * columns column of the rows row and find the return true, otherwise, false bool IsFind (int * p_nArray, int rows, int columns, int nFindNum) {assert (p_nArray! = NULL & rows> 0 & columns> 0); if (p_nArray! = NULL & rows> 0 & columns> 0) {int row = 0; int column = columns-1; while (row <rows & column> = 0) {if (* (p_nArray + row * columns + column) = nFindNum) {return true;} else if (* (p_nArray + row * columns + column)> nFindNum) {-- column;} else {++ row;} return false;} else {return false;} int _ tmain (int argc, _ TCHAR * argv []) {int nArr [4] [4] = {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13 },{ 6, 8, 11, 15 }}; cout <IsFind (* nArr, 4, 4, 7) <endl; cout <IsFind (* nArr, 4, 4, 0) <endl; // For a two-dimensional array, the row pointer plus 1 skips a row, and the column pointer plus 1 skips an element system ("pause "); return 0 ;}</SPAN> # include "stdafx. h "# include <assert. h> # include <iostream> using namespace std; // search for nFindNum in the two-dimensional array p_nArray in the * columns column of the rows row, and return true; otherwise, return falsebool IsFind (int * p_nArray, int rows, int columns, int nFindNum) {assert (p_nArray! = NULL & rows> 0 & columns> 0); if (p_nArray! = NULL & rows> 0 & columns> 0) {int row = 0; int column = columns-1; while (row <rows & column> = 0) {if (* (p_nArray + row * columns + column) = nFindNum) {return true;} else if (* (p_nArray + row * columns + column)> nFindNum) {-- column;} else {++ row;} return false;} else {return false;} int _ tmain (int argc, _ TCHAR * argv []) {int nArr [4] [4] = {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13 },{ 6, 8, 11, 15 }}; cout <IsFind (* nArr, 4, 4, 7) <endl; cout <IsFind (* nArr, 4, 4, 0) <endl; // For a two-dimensional array, the row pointer plus 1 skips a row, and the column pointer plus 1 skips an element system ("pause "); return 0 ;}