Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Shavit Borisov
- // CW
- import java.util.Scanner;
- public class BinarySearch {
- static Scanner in = new Scanner(System.in);
- public static void main(String[] args)
- {
- final int SIZE = 3;
- int[] array = new int[SIZE];
- getData(array);
- int key = -1;
- int currentResult;
- System.out.printf("What is your key? Enter 0 to stop the procedure. ");
- key = in.nextInt();
- while(key != 0)
- {
- currentResult = Bsearch(array, key);
- if(currentResult == -1)
- System.out.printf("Key not found\n");
- else
- System.out.printf("Key found in array[%d]\n", currentResult);
- System.out.printf("What is your next key? ");
- key = in.nextInt();
- }
- in.close();
- }
- private static void getData(int[] array)
- {
- for(int i = 0; i < array.length; i++)
- {
- System.out.printf("Enter value for array[%d]: ", i);
- array[i] = in.nextInt();
- }
- }
- private static int Bsearch(int[] array, int key)
- {
- int middle;
- int low = 0;
- int high = array.length - 1;
- while(low <= high)
- {
- middle = (low + high) / 2;
- if(array[middle] == key)
- return middle;
- else
- {
- if(array[middle] > key)
- high = middle - 1;
- else
- low = middle + 1;
- }
- }
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement