|
1 | 1 | package com.thealgorithms.searches;
|
2 | 2 |
|
3 |
| -class PerfectBinarySearch { |
| 3 | +import com.thealgorithms.devutils.searches.SearchAlgorithm; |
4 | 4 |
|
5 |
| - static int binarySearch(int[] arr, int target) { |
6 |
| - int low = 0; |
7 |
| - int high = arr.length - 1; |
| 5 | +/** |
| 6 | + * Binary search is one of the most popular algorithms The algorithm finds the |
| 7 | + * position of a target value within a sorted array |
| 8 | + * |
| 9 | + * <p> |
| 10 | + * Worst-case performance O(log n) Best-case performance O(1) Average |
| 11 | + * performance O(log n) Worst-case space complexity O(1) |
| 12 | + * |
| 13 | + * @author D Sunil (https://github.com/sunilnitdgp) |
| 14 | + * @see SearchAlgorithm |
| 15 | + */ |
8 | 16 |
|
9 |
| - while (low <= high) { |
10 |
| - int mid = (low + high) / 2; |
| 17 | +public class PerfectBinarySearch<T> implements SearchAlgorithm { |
11 | 18 |
|
12 |
| - if (arr[mid] == target) { |
13 |
| - return mid; |
14 |
| - } else if (arr[mid] > target) { |
15 |
| - high = mid - 1; |
| 19 | + /** |
| 20 | + * @param array is an array where the element should be found |
| 21 | + * @param key is an element which should be found |
| 22 | + * @param <T> is any comparable type |
| 23 | + * @return index of the element |
| 24 | + */ |
| 25 | + @Override |
| 26 | + public <T extends Comparable<T>> int find(T[] array, T key) { |
| 27 | + return search(array, key, 0, array.length - 1); |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * This method implements the Generic Binary Search iteratively. |
| 32 | + * |
| 33 | + * @param array The array to make the binary search |
| 34 | + * @param key The number you are looking for |
| 35 | + * @return the location of the key, or -1 if not found |
| 36 | + */ |
| 37 | + private static <T extends Comparable<T>> int search(T[] array, T key, int left, int right) { |
| 38 | + while (left <= right) { |
| 39 | + int median = (left + right) >>> 1; |
| 40 | + int comp = key.compareTo(array[median]); |
| 41 | + |
| 42 | + if (comp == 0) { |
| 43 | + return median; // Key found |
| 44 | + } |
| 45 | + |
| 46 | + if (comp < 0) { |
| 47 | + right = median - 1; // Adjust the right bound |
16 | 48 | } else {
|
17 |
| - low = mid + 1; |
| 49 | + left = median + 1; // Adjust the left bound |
18 | 50 | }
|
19 | 51 | }
|
20 |
| - return -1; |
21 |
| - } |
22 |
| - |
23 |
| - public static void main(String[] args) { |
24 |
| - int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; |
25 |
| - assert PerfectBinarySearch.binarySearch(array, -1) == -1; |
26 |
| - assert PerfectBinarySearch.binarySearch(array, 11) == -1; |
| 52 | + return -1; // Key not found |
27 | 53 | }
|
28 | 54 | }
|
0 commit comments