Advertisement
glee20

Binary Search

Oct 4th, 2018
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1. class BinarySearch {
  2.     public static void main (String args[]) {
  3.         int values[] = {11, 12, 15, 16, 112, 118, 123, 145};
  4.         int target = 15;
  5.         int min = 0;
  6.         int high = 7;
  7.         boolean found = false;
  8.         int answer = 0;
  9.         int mid = 0;
  10.         while ((found==false)&&(min<=high)) {
  11.             mid = ((min+high)/2);
  12.             if (values[mid]==target) {
  13.                 found = true;
  14.                 answer = min;
  15.             }
  16.             else if (target>values[mid]) {
  17.                 min = mid+1;
  18.             }
  19.             else {
  20.                 high = mid-1;
  21.             }
  22.         }
  23.         if (found == true) {
  24.             System.out.println(target + " found at array index " + answer + ".");
  25.         }
  26.         else {
  27.             System.out.println(target + " was not found.");
  28.         }
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement