search_1.png
search_2.png
/**
* Abstract: take a[][] as a[]
*/
bool bi_search(int** matrix, int matrixSize, int* matrixColSize, int target, int lo, int hi) {
if (lo >= hi) return false;
int mid = (lo + hi) / 2, j = mid % *matrixColSize, i = mid / *matrixColSize;
if (matrix[i][j] == target) return true;
if (matrix[i][j] > target) {
return bi_search(matrix, matrixSize, matrixColSize, target, lo, mid);
} else {
return bi_search(matrix, matrixSize, matrixColSize, target, mid + 1, hi);
}
}
bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target) { return bi_search(matrix, matrixSize, matrixColSize, target, 0, matrixSize * *matrixColSize); }
网友评论