Advertisement
solokiller11

Ex14.2 - Lee /w comments

Jan 11th, 2022
890
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. /**
  2.      * Check if matrix of integers contains a number
  3.      * @param mat - a two-dimentional array to seach in
  4.      * @param num - the number to seach for
  5.      * @return true if the number is found, false otherwise
  6.      *
  7.      * Time Compelxity - O(logn)
  8.      * Space Complexity - O(1)
  9.      */
  10.     public static boolean search(int[][] mat, int num)
  11.     {
  12.         // low and high values to track searching bounds
  13.         int rL = 0, rH = mat.length;
  14.         int cL = 0, cH = mat.length;
  15.        
  16.         // center pivot
  17.         int pR = rL + (rH - rL)/2;
  18.         int pC = cL + (cH - cL) / 2;
  19.        
  20.        
  21.         while(mat[pR][pC] != num)
  22.         {
  23.             // if the lower and upper bounds are equals we are done scanning
  24.             if(rH == rL || cH == cL)
  25.                 return false;
  26.            
  27.             // setting pivots to matrix center value
  28.             pR = rL + (rH - rL)/2;
  29.             pC = cL + (cH - cL) / 2;
  30.            
  31.             // checking lower left quadrant
  32.             if(num >= mat[pR][cL])
  33.             {
  34.                 rL = pR;
  35.                 cH = pC;
  36.             }  
  37.             // checking lower right quadrant
  38.             else if(num >= mat[pR][pC])
  39.             {
  40.                 rL = pR;
  41.                 cL = pC;
  42.             }
  43.             // checking upper right quadrant
  44.             else if(num >= mat[rL][pC])
  45.             {
  46.                 rH = pR;
  47.                 cL = pC;
  48.             }
  49.             // checking upper left quadrant
  50.             else
  51.             {
  52.                 rH = pR;
  53.                 cH = pC;
  54.             }
  55.         }
  56.        
  57.         return true;
  58.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement