Created
July 28, 2011 13:04
-
-
Save margusmartsepp/1111497 to your computer and use it in GitHub Desktop.
binary search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Function returns location of unique item in a sorted list. | |
| * | |
| * @param <T> Class, that implements comparable interface. | |
| * @param data list of elements | |
| * @param searchValue element to search for | |
| * @return Location of the the element. If item is not found, -1 is returned. | |
| * @throws java.lang.NullPointerException | |
| * If any checked element in the list is 'null'. | |
| */ | |
| public static <T extends Comparable<? super T>> // | |
| int binarySearch(final List<T> data, T searchValue) | |
| throws java.lang.NullPointerException { | |
| return binarySearch(data, searchValue, 0, data.size() - 1); | |
| } | |
| /** | |
| * Function returns location of unique item in a sorted list. | |
| * | |
| * @param <T> Class, that implements comparable interface. | |
| * @param data list of elements | |
| * @param searchValue element to search for | |
| * @param left lower bound | |
| * @param right upper bound | |
| * @return Location of the the element. If item is not found, -1 is returned. | |
| * @throws java.lang.NullPointerException | |
| * If any checked element in the list is 'null'. | |
| */ | |
| public static <T extends Comparable<? super T>> // | |
| int binarySearch(final List<T> data, T searchValue, int left, int right) | |
| throws java.lang.NullPointerException { | |
| final int NOT_FOUND = -1; | |
| if (right < left) | |
| return NOT_FOUND; | |
| int mid = (left + right) >>> 1; | |
| int cmp = searchValue.compareTo(data.get(mid)); | |
| if (cmp > 0) | |
| return binarySearch(data, searchValue, mid + 1, right); | |
| if (cmp < 0) | |
| return binarySearch(data, searchValue, left, mid - 1); | |
| return mid; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment