Search in 2D array - Java
public class SearchInSorted2D {
public static boolean search(int[][] sorted, int k) {
int x = sorted.length-1;
int y = 0;
boolean found = false;
while(x>=0 && y<=sorted[0].length-1){
if(sorted[x][y] > k)
x--;
else if(sorted[x][y] < k)
y++;
else {
found = true;
break;
}
}
return found;
}
public static void main(String[] args) {
int[][] sorted = {{1,4,5,10},{2,6,7,12},{3,8,9,15}};
System.out.println(search(sorted, 12));
}
}
output:
true
public static boolean search(int[][] sorted, int k) {
int x = sorted.length-1;
int y = 0;
boolean found = false;
while(x>=0 && y<=sorted[0].length-1){
if(sorted[x][y] > k)
x--;
else if(sorted[x][y] < k)
y++;
else {
found = true;
break;
}
}
return found;
}
public static void main(String[] args) {
int[][] sorted = {{1,4,5,10},{2,6,7,12},{3,8,9,15}};
System.out.println(search(sorted, 12));
}
}
output:
true
Comments
Post a Comment