Mentor Graphics Interview Question
MTSsCountry: India
Interview Type: In-Person
public static void findInArray(int[][] inpArr, int num) {
int count = 1;
boolean flag = true;
int i = 0;
int j = (inpArr[0].length)-1;
int currentNum = inpArr[i][j];
while(num!=currentNum) {
count++;
if(num>currentNum) {
i++;
} else {
j--;
}
try {
currentNum = inpArr[i][j];
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println(num + " not found in input array");
flag = false;
break;
}
}
if(flag) System.out.println(num + "fount at (" + i +","+ j + ") position in " + count + " comparision(s).");
}
While this solution is correct, it does not make use of sorted columns and rows.
Following is the algo:
1. Look along diagonal for element greater than element to be found. Let's call this point (row, col) as pivot.
2. The pivot point cuts the array into 4 quadrant. Our element can only be present in the quadrant that is
2(a) above and towards right
2(b) below and towards left of this pivot point.
3. Apply this recursively to get the ans.
1)start from top right corner
- Yoda July 15, 20122) until curr_elem==elem_to_search || you go out of matrix, go down if curr_elem<elem_to_search else go left
complexity= O(m+n)