- #include
using namespace std;
int getFirstBigger(int intarr[], int length,int key)
{
int left = 0;
int right = length - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (intarr[mid] > key)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return left;
}
bool getEquleFirst(int intarr[], int length, int key)
{
int left = 0;
int right = length - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (intarr[mid] == key)
{
return true;
}
if (intarr[mid] > key)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return false;
}
int matrix[3][4] =
{
{1,3,5,7},
{10,11,16,20},
{23,30,34,50},
};
bool isInMatrix(int key)
{
int left = 0;
int right = 3 - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (matrix[mid][0] == key)
{
return true;
}
if (matrix[mid][0] > key)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
if (left == 0)
{
return false;
}
return getEquleFirst(matrix[left-1],4,key);
}
bool isInMatrixHer(int key)
{
int len = 3 * 4;
int left = 0;
int right = len - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (matrix[mid / 4][mid % 4] == key)
{
return true;
}
if (matrix[mid / 4][mid % 4] > key)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return false;
}
int main()
{
int intarr[10] = { 1,5,9,11,15,16,25,26,29,34 };
cout << getFirstBigger(intarr, 10, 50) << endl;
cout << isInMatrix(100) << endl;
cout << isInMatrixHer(50) << endl;
system(“pause”);
return 0;
}
Search a 2D Matrix 搜索一个二维矩阵
最新推荐文章于 2022-01-29 09:30:55 发布