Advertisement
Shavit

P. 133 Ex. 4

Mar 21st, 2014
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. // Shavit Borisov
  2. // CW
  3.  
  4. import java.util.Scanner;
  5.  
  6. public class BinarySearch {
  7.  
  8.     static Scanner in = new Scanner(System.in);
  9.  
  10.     public static void main(String[] args)
  11.     {
  12.         final int SIZE = 3;
  13.         int[] array = new int[SIZE];
  14.         getData(array);
  15.         int key = -1;
  16.        
  17.         int currentResult;
  18.        
  19.         System.out.printf("What is your key? Enter 0 to stop the procedure. ");
  20.         key = in.nextInt();
  21.        
  22.         while(key != 0)
  23.         {
  24.             currentResult = Bsearch(array, key);
  25.             if(currentResult == -1)
  26.                 System.out.printf("Key not found\n");
  27.             else
  28.                 System.out.printf("Key found in array[%d]\n", currentResult);
  29.            
  30.             System.out.printf("What is your next key? ");
  31.             key = in.nextInt();
  32.         }
  33.         in.close();
  34.     }
  35.    
  36.     private static void getData(int[] array)
  37.     {
  38.         for(int i = 0; i < array.length; i++)
  39.         {
  40.             System.out.printf("Enter value for array[%d]: ", i);
  41.             array[i] = in.nextInt();
  42.         }
  43.     }
  44.    
  45.     private static int Bsearch(int[] array, int key)
  46.     {
  47.         int middle;
  48.         int low = 0;
  49.         int high = array.length - 1;
  50.         while(low <= high)
  51.         {
  52.             middle = (low + high) / 2;
  53.             if(array[middle] == key)
  54.                 return middle;
  55.             else
  56.             {
  57.                 if(array[middle] > key)
  58.                     high = middle - 1;
  59.                 else
  60.                     low = middle + 1;
  61.             }
  62.         }
  63.         return -1;
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement