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