Advertisement
Guest User

RecursiveBinarySearch

a guest
Apr 24th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.09 KB | None | 0 0
  1. /**
  2.    An methods for a recursive binary search. Searches for both halves of an array and returns the larger of the two.
  3.  */
  4. public class RecursiveBinarySeach
  5. {
  6.    /** Searches for a specified entry in an array.
  7.     *  @param anArray  The array to be searched.
  8.     *  @param first    First entry in the array.
  9.     *  @param last     Last entry in the array.
  10.     *  @param index    Position inside the array while searching.
  11.     *  @param largest1 The largest element in the first half of the array.
  12.     *  @param largest2 The largest element in the second half of the array.
  13.     *  @return  Returns the largest element in the array. This can be either largest1 or largest2
  14.                 depending on which of the two is larger.
  15.     */  
  16.    private static <T extends Comparable<? super T>> T binarySearch(T[] anArray, int first, int last, int index, T largest1, T largest2)
  17.    {
  18.       int mid = first + (last - first) / 2;
  19.      
  20.       if (index < mid)
  21.       {
  22.          if (largest1.compareTo(anArray[index]) < 0)
  23.          {
  24.             largest1 = anArray[index];
  25.          }
  26.          return binarySearch(anArray, first, last, index++, largest1, largest2);
  27.       }
  28.       else if (index >= mid && index <= anArray.length)
  29.       {
  30.          if (largest2.compareTo(anArray[index]) < 0)
  31.          {
  32.             largest1 = anArray[index];
  33.          }
  34.          return binarySearch(anArray, first, last, index++, largest1, largest2);
  35.       }
  36.       else
  37.       {
  38.          if (largest1.compareTo(largest2) > 0)
  39.          {
  40.             return largest1;
  41.          }
  42.          else
  43.          {
  44.             return largest2;
  45.          }
  46.       }
  47.    }
  48.    
  49.    /** Helper method for binarySearch().
  50.     *  @param anArray  The array to be searched.
  51.     *  @return  Returns the largest element in the array. This can be either largest1 or largest2
  52.                 depending on which of the two is larger.
  53.     */  
  54.    public static <T extends Comparable<? super T>> T binarySearch(T[] anArray)
  55.    {
  56.       return binarySearch(anArray, 0, anArray.length - 1, 0, anArray[0], anArray[anArray.length - 1]);
  57.    }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement