Advertisement
solokiller11

Ex14.2 - Lee

Dec 26th, 2021
1,166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | None | 0 0
  1.  
  2. /**
  3.  * Write a description of class Ex14 here.
  4.  *
  5.  * @author (your name)
  6.  * @version (a version number or a date)
  7.  */
  8. public class Ex14
  9. {
  10.     private static final int DEFAULT_VAL = -1;
  11.    
  12.     public static int findMinDiff(int[] a, int x, int y)
  13.     {
  14.         int iX = DEFAULT_VAL;
  15.         int iY = DEFAULT_VAL;
  16.         int dist = DEFAULT_VAL;
  17.        
  18.         for(int i = 0; i < a.length; i++)
  19.         {
  20.             if(a[i] == x)
  21.             {
  22.                 iX = i;
  23.             }
  24.             else if(a[i] == y)
  25.             {
  26.                 iY = i;
  27.             }
  28.            
  29.             if(iX != -1 && iY != -1)
  30.             {
  31.                 dist = Math.abs(iX - iY);
  32.             }
  33.         }
  34.        
  35.         if(dist == DEFAULT_VAL)
  36.         {
  37.             return Integer.MAX_VALUE;
  38.         }
  39.        
  40.         return dist;
  41.     }
  42.    
  43.     public static boolean search(int[][] mat, int num)
  44.     {
  45.         int rL = 0, rH = mat.length;
  46.         int cL = 0, cH = mat.length;
  47.         int pR = rL + (rH - rL)/2;
  48.         int pC = cL + (cH - cL) / 2;
  49.        
  50.         for(int i = 0; i < Math.log(mat.length)/Math.log(2); i++)
  51.         {
  52.             pR = rL + (rH - rL)/2;
  53.             pC = cL + (cH - cL) / 2;
  54.             if(num >= mat[pR][cL])
  55.             {
  56.                 rL = pR;
  57.                 cH = pC;
  58.             }  
  59.             else if(num >= mat[pR][pC])
  60.             {
  61.                 rL = pR;
  62.                 cL = pC;
  63.             }            
  64.             else if(num >= mat[rL][pC])
  65.             {
  66.                 rH = pR;
  67.                 cL = pC;
  68.             }
  69.             else
  70.             {
  71.                 rH = pR;
  72.                 cH = pC;
  73.             }
  74.         }
  75.        
  76.         pR = rL + (rH - rL)/2;
  77.         pC = cL + (cH - cL) / 2;
  78.         return mat[pR][pC] == num;
  79.     }
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement