Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- An methods for a recursive binary search. Searches for both halves of an array and returns the larger of the two.
- */
- public class RecursiveBinarySeach
- {
- /** Searches for a specified entry in an array.
- * @param anArray The array to be searched.
- * @param first First entry in the array.
- * @param last Last entry in the array.
- * @param index Position inside the array while searching.
- * @param largest1 The largest element in the first half of the array.
- * @param largest2 The largest element in the second half of the array.
- * @return Returns the largest element in the array. This can be either largest1 or largest2
- depending on which of the two is larger.
- */
- private static <T extends Comparable<? super T>> T binarySearch(T[] anArray, int first, int last, int index, T largest1, T largest2)
- {
- int mid = first + (last - first) / 2;
- if (index < mid)
- {
- if (largest1.compareTo(anArray[index]) < 0)
- {
- largest1 = anArray[index];
- }
- return binarySearch(anArray, first, last, index++, largest1, largest2);
- }
- else if (index >= mid && index <= anArray.length)
- {
- if (largest2.compareTo(anArray[index]) < 0)
- {
- largest1 = anArray[index];
- }
- return binarySearch(anArray, first, last, index++, largest1, largest2);
- }
- else
- {
- if (largest1.compareTo(largest2) > 0)
- {
- return largest1;
- }
- else
- {
- return largest2;
- }
- }
- }
- /** Helper method for binarySearch().
- * @param anArray The array to be searched.
- * @return Returns the largest element in the array. This can be either largest1 or largest2
- depending on which of the two is larger.
- */
- public static <T extends Comparable<? super T>> T binarySearch(T[] anArray)
- {
- return binarySearch(anArray, 0, anArray.length - 1, 0, anArray[0], anArray[anArray.length - 1]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement