搜索二维矩阵(二分法)
#include <stdio.h>
#include <stdbool.h>
bool searchMatrix(int (*matrix)[4], int matrixrow, int *matrixcol, int target);
int main()
{
int matrix[][4] = {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}};
int target = 13;
int matrixrow = 3;
int matrixcol = 4;
bool flag = searchMatrix(matrix, matrixrow, &matrixcol, target);
if(flag == false)
printf("false");
else
printf("true");
}
bool searchMatrix(int (*matrix)[4], int matrixrow, int *matrixcol, int target)
{
//验证指针是否为空以及行数
if(matrix == NULL || matrixrow == 0)
return false;
int row = matrixrow;
int col = *matrixcol;
int left = 0;
int right = row * col - 1;
int mid = 0;
int elm = 0;
while(left <= right)
{
mid = (left + right) >> 1; //除以2
//两种方式
// elm = matrix[mid / col][mid % col];
elm = *(*(matrix + mid / col) + mid % col);
if(elm == target)
return true;
else if(elm >= target)
right = mid - 1;
else
left = mid + 1;
}
return false;
}