|
| 1 | +package src.main.com.java.search; |
| 2 | + |
| 3 | +/** |
| 4 | + * Binary search is an algorithm which finds the position of a target value within a sorted array |
| 5 | + * |
| 6 | + * Worst-case performance O(log n) |
| 7 | + * Best-case performance O(1) |
| 8 | + * Average performance O(log n) |
| 9 | + * Worst-case space complexity O(1) |
| 10 | + */ |
| 11 | +public class BinarySearch { |
| 12 | + |
| 13 | + /** |
| 14 | + * @param array is an array where the element should be found |
| 15 | + * @param key is an element which should be found |
| 16 | + * @param <T> is any comparable type |
| 17 | + * @return index of the element |
| 18 | + */ |
| 19 | + public <T extends Comparable<T>> int findIndex(T array[], T key) { |
| 20 | + return search(array, key, 0, array.length-1); |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * @param array The array to make the binary search |
| 25 | + * @param key The number you are looking for |
| 26 | + * @param left The lower bound |
| 27 | + * @param right The upper bound |
| 28 | + * @return the location of the key |
| 29 | + **/ |
| 30 | + private <T extends Comparable<T>> int search(T array[], T key, int left, int right){ |
| 31 | + if (left > right) { |
| 32 | + return -1; // Key not found |
| 33 | + } |
| 34 | + |
| 35 | + // Find median |
| 36 | + int median = (left + right)/2; |
| 37 | + int comp = key.compareTo(array[median]); |
| 38 | + |
| 39 | + if (comp < 0) { |
| 40 | + return search(array, key, left, median - 1); |
| 41 | + } |
| 42 | + |
| 43 | + if (comp > 0) { |
| 44 | + return search(array, key, median + 1, right); |
| 45 | + } |
| 46 | + |
| 47 | + return median; |
| 48 | + } |
| 49 | +} |
0 commit comments