Cracking the coding interview 9.6
Given a matrix in which each row and each column is sorted. write a method to find an element in it. implement a function to find whether an element exists in a two-dimensional array sorted by rows and columns.
Idea: If the element to be searched is smaller than the leftmost element in a row or the rightmost element in a row, the element to be searched cannot exist in the current row. The same applies to columns. Determine whether the element to be searched may exist in the four directions from top to bottom, and from the outer to the inside. Gradually narrow the search scope.
/** * Search specific value in sorted 2D array, which both row and column are sorted in ascending order. * *arr: address of a array, row-major order stored *nRow: row of input array *nColumn: column of input array *nVal: the value that to be searched */bool SearchSorted2D(int *arr, const int nRow, const int nColumn, const int nVal){int nTop = 0;int nBottom = nRow - 1;int nLeft = 0;int nRight = nColumn - 1;while ((nTop <= nBottom) && (nLeft <= nRight)){// Compare with the most top-left(smallest) and the most bottom-right(biggest) element.if (nVal < (*(arr+nColumn*nTop+nLeft)) || (nVal > (*(arr+nColumn*nBottom+nRight))))return false;if (*(arr+nColumn*nTop+nRight) == nVal){printf("arr[%d][%d]=%d\n", nTop, nRight, *(arr+nColumn*nTop+nRight));return true;}if (*(arr+nColumn*nBottom+nLeft) == nVal){printf("arr[%d][%d]=%d\n", nBottom, nLeft, *(arr+nColumn*nBottom+nLeft));return true;}if ((nTop == nBottom) && (nLeft == nRight))return false;//////////////////////////////////// Search from top-right corner// the most right element of row is smaller than nVal, then the whole row is smaller than nValif (*(arr+nColumn*nTop+nRight) < nVal)nTop ++;// the most top element of column is bigger than nVal, then the whole column is smaller than nValif (*(arr+nColumn*nTop+nRight) > nVal)nRight --;//////////////////////////////////// Search from bottom-left corner// the most bottom element of column is smaller than nVal, then the whole column is smaller than nValif (*(arr+nColumn*nBottom+nLeft) < nVal)nLeft ++;// the most left element of row is smaller than nVal, then the whole row is smaller than nValif (*(arr+nColumn*nBottom+nLeft) > nVal)nBottom --;}return false;}