Advertisement
alisadafi

Matrix-Search-Efficient

Nov 9th, 2023
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Main {
  4.     public static void main(String[] args) {
  5.         // Example usage
  6.         int[][] X = {
  7.             {1, 2, 3},
  8.             {4, 5, 6},
  9.             {7, 8, 9}
  10.         };
  11.         int k = 5;
  12.         Pair<Integer, Integer> result = find(X, k);
  13.         if (result.getKey() == -1 && result.getValue() == -1) {
  14.             System.out.println("Element not found.");
  15.         } else {
  16.             System.out.printf("Element found at position (%d, %d).\n", result.getKey(), result.getValue());
  17.         }
  18.     }
  19.  
  20.     public static Pair<Integer, Integer> find(int[][] X, int k) {
  21.         int n = X.length;
  22.         int m = X[0].length;
  23.         int a = 0;
  24.         int b = m - 1;
  25.         while (a < n && b >= 0) {
  26.             if (X[a][b] == k) {
  27.                 break;
  28.             } else if (X[a][b] < k) {
  29.                 a += 1;
  30.             } else {
  31.                 b -= 1;
  32.             }
  33.         }
  34.         if (a >= n || b < 0) {
  35.             return new Pair<>(-1, -1);  // not found
  36.         }
  37.         return new Pair<>(a, b);
  38.     }
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement