Advertisement
STANAANDREY

find in mat dei2

Oct 12th, 2020 (edited)
2,087
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. /*sa se scrie un program ce foloseste un subprog. recursiv cu metoda DEI ce afiseaza pozitia pe care se gaseste un element x in matrice */
  2. #include <iostream>
  3. #define NMAX 100
  4. using namespace std;
  5.  
  6. void readVar(char varname, int &var) {
  7.     cout << varname << '=';
  8.     cin >> var;
  9. }
  10.  
  11. void readMat(int &n, int &m, int a[][NMAX]) {
  12.     readVar('n', n);
  13.     readVar('m', m);
  14.     for (int i = 0; i < n; i++)
  15.         for (int j = 0; j < m; j++)
  16.             cin >> a[i][j];
  17. }
  18.  
  19. int findInV(int v[], int p, int q, int x) {
  20.     if (p > q)
  21.         return -1;
  22.     int mid = (p + q) / 2;
  23.         if (v[mid] == x)
  24.             return mid;
  25.     int pos = findInV(v, p, mid - 1, x);
  26.     return pos == -1 ? findInV(v, mid + 1, q, x) : pos;
  27. }
  28.  
  29. void findInM(int a[][NMAX], int p, int q, int x, int m) {
  30.     if (p > q)
  31.         return;
  32.     int mid = (p + q) / 2;
  33.     int pos = findInV(a[mid], 0, m - 1, x);
  34.     if (pos != -1) {
  35.         cout << mid << ' ' << pos << endl;
  36.         return;
  37.     }
  38.     findInM(a, p, mid - 1, x, m);
  39.     findInM(a, mid + 1, q, x, m);
  40. }
  41.  
  42. int n, m, a[NMAX][NMAX], x;
  43. int main() {
  44.     readMat(n, m, a);
  45.     readVar('x', x);
  46.     findInM(a, 0, n - 1, x, m);
  47.     return 0;
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement