'Search for an element in a circular sorted 2d matrix
I was given a question in my class that I just can't get my head around it. I've been trying for days and can't think of a logic that works 100%
The question is: Search for an element in a circular sorted 2d matrix, example below:

We were asked to do it with the best complexity available. I've figured out that the rows are sorted by size, But this theory failed.
I've figured if I'll find the middle element, I could move the pointer accordingly, but it makes no sense.
I was thinking that maybe I should find each quadrant's start index and last index, and search inside, but I don't know how to do that with a 2d array
Here's my piece of code that I crafted so far (It's useless)
public static boolean search (int [][] mat, int num) {
int midRowIndex =(mat.length-1)/2;
int midColIndex =(mat[0].length-1)/2;
int start = 0;
int end =(mat.length*mat[0].length)-1;
System.out.println("Mid index is: [" +midColIndex + "][" + midRowIndex + "]");
System.out.println("Number of indexes is: " +end);
System.out.println("Searching for: " +num );
while (start<end) {
if (mat[midRowIndex][midColIndex] == num)
return true;
if (mat[midRowIndex][midColIndex] < num)
if(midColIndex < mat.length)
midColIndex+=1;
else{
midColIndex=0;
midRowIndex+=1;
}
if (mat[midRowIndex][midColIndex] > num)
midRowIndex-=1;
start+=1;
}
return false;
}
I'm not asking for a direct answer, Just for some leads.
Thanks!
Solution 1:[1]
what you can do here is a variation of binary search.
Here is the algorithm (maybe it has minor mistakes but this is the general idea):
For matrix a of size n x n, and searched value s:
evenIteration = true //as in even/odd
startX, startY = 0
endX, endY = n
while(endX >= startX && endY >= startY):
middleY = ((endY + startY)/2)
middleX = ((endX + startX)/2)
if evenIteration:
i = middleY - 1
j = middleX
Else:
i = endY - 1
j = startX
candidate = a[i][j]
if s == candidate:
Return i,j // We found the searched value!
if s < candidate:
if evenIteration:
endY = middleY
else:
endX = middleX
else:
if evenIteration:
startY = middleY
else:
startX = middleX
evenIteration = !evenIteration
Try understanding the logic behind this, and implement this in code. Write unit tests and debug the code. this would help you understand the algorithm better.
Let me know in the comments if you need further explanation
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Orr Benyamini |
