Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class BinarySearch {
- public static void main(String[] args)
- {
- int[] ary = new int[]{1,4,2,8,4,3,1};
- Arrays.sort(ary);
- int targetElmt = 4;
- int i = binarySearch(ary, 0, ary.length - 1, targetElmt);
- System.out.println("");
- }
- static int binarySearch(int[] ary, int lowerIndex, int higherIndex, int value) {
- if (lowerIndex > higherIndex) {
- // The starting position comes after the final index,
- // so there are actually no elements in the specified
- // range. The value does not occur in this empty list!
- return -1;
- } else {
- // Look at the middle position in the list. If the
- // value occurs at that position, return that position.
- // Otherwise, search recursively in either the first
- // half or the second half of the list.
- int middle = (lowerIndex + higherIndex) / 2;
- if (value == ary[middle])
- return middle;
- else if (value < ary[middle])
- return binarySearch(ary, lowerIndex, middle - 1, value);
- else // value must be > A[middle]
- return binarySearch(ary, middle + 1, higherIndex, value);
- } // end binarySearch()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement