Advertisement
uopspop

Untitled

Sep 13th, 2019
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class BinarySearch {
  4.     public static void main(String[] args)
  5.     {
  6.         int[] ary = new int[]{1,4,2,8,4,3,1};
  7.         Arrays.sort(ary);
  8.         int targetElmt = 4;
  9.         int i = binarySearch(ary, 0, ary.length - 1, targetElmt);
  10.         System.out.println("");
  11.     }
  12.  
  13.     static int binarySearch(int[] ary, int lowerIndex, int higherIndex, int value) {
  14.         if (lowerIndex > higherIndex) {
  15.             // The starting position comes after the final index,
  16.             // so there are actually no elements in the specified
  17.             // range.  The value does not occur in this empty list!
  18.             return -1;
  19.         } else {
  20.             // Look at the middle position in the list.  If the
  21.             // value occurs at that position, return that position.
  22.             // Otherwise, search recursively in either the first
  23.             // half or the second half of the list.
  24.             int middle = (lowerIndex + higherIndex) / 2;
  25.             if (value == ary[middle])
  26.                 return middle;
  27.             else if (value < ary[middle])
  28.                 return binarySearch(ary, lowerIndex, middle - 1, value);
  29.             else   // value must be > A[middle]
  30.                 return binarySearch(ary, middle + 1, higherIndex, value);
  31.         } // end binarySearch()
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement