-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearchAMatrix.java
More file actions
36 lines (34 loc) · 1.09 KB
/
Copy pathsearchAMatrix.java
File metadata and controls
36 lines (34 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//Question: Search a given number(Turget) in the matrix.
// The matrix is sorted in ascending order. (Row-> left to right, Column-> top to bottom)
package twoDArray;
import java.util.Scanner;
public class searchAMatrix {
public static void main(String[] args) {
int [][] arr={{1,4,7,11,15},{2,5,8,12,19},{3,6,9,16,22},{10,13,14,17,24},{18,21,23,26,30}};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j]+" ");
} System.out.println();
}
System.out.println("Enter the turget element: ");
Scanner sc=new Scanner(System.in);
int turget=sc.nextInt();
boolean bool=false;
int i=0, j=arr[0].length-1;
while(i<arr.length && j>=0){
if(arr[i][j]==turget) {
bool=true;
break;
}else if(arr[i][j]<turget){
i++;
}else if(arr[i][j]>turget){
j--;
}
}
if(bool==true){
System.out.println("Element Found");
}else{
System.out.println("Element not found");
}
}
}