For example, given a 2D array (a matrix):
{{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}}
What are the solutions to find a number, such as 6?
Here's the code I tried using binary search method:
int main(){
int sample[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int target = 6;
int lowX, highX, lowY, highY, midX, midY;
//Note: some values are hardcoded, should not matter.
lowX = 0;
highX = 2;
lowY = 0;
highY = 3;
if(target <= sample[0][0] || target >= sample[3 - 1][4 - 1]){
std::cout<<"Nope";
}
while(lowX <= highX && lowY <= highY){
midX = (lowX + highX)/2;
midY = (lowY + highY)/2;
if(target < sample[midX][midY]){
highX = midX - 1;
highY = midY - 1;
}
else if(target > sample[midX][midY]){
lowX = highX + 1;
lowY = highY + 1;
}
else {
lowX = highX + 1;
lowY = highY + 1;
}
}
if(target == sample[midX][midY]){
std::cout<<"Found";
}
else{
std::cout<<"Nope";
}
return 0;
}
Is this method optimal? What are the other possible solutions?