Advertisement
alisadafi

Matrix-Search-Efficient

Nov 9th, 2023
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. pair<int, int> find(vector<vector<int>>& X, int k) {
  7.     int n = X.size();
  8.     int m = X[0].size();
  9.     int a = 0;
  10.     int b = m - 1;
  11.     while (a < n && b >= 0) {
  12.         if (X[a][b] == k) {
  13.             break;
  14.         } else if (X[a][b] < k) {
  15.             a += 1;
  16.         } else {
  17.             b -= 1;
  18.         }
  19.     }
  20.     if (a >= n || b < 0) {
  21.         return make_pair(-1, -1);  // not found
  22.     }
  23.     return make_pair(a, b);
  24. }
  25.  
  26. int main() {
  27.     vector<vector<int>> X = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
  28.     int k = 5;
  29.     pair<int, int> result = find(X, k);
  30.     if (result.first == -1 && result.second == -1) {
  31.         cout << "Element not found." << endl;
  32.     } else {
  33.         cout << "Element found at position (" << result.first << ", " << result.second << ")." << endl;
  34.     }
  35.     return 0;
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement