Skip to content

Commit 5227629

Browse files
authored
Merge pull request TheAlgorithms#706 from crackCodeLogn/Development
Making the median calculating part safe from integer spillovers
2 parents 50c7ba4 + 5c94611 commit 5227629

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

src/main/java/com/search/BinarySearch.java

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,38 +2,38 @@
22

33
/**
44
* Binary search is an algorithm which finds the position of a target value within a sorted array
5-
*
5+
* <p>
66
* Worst-case performance O(log n)
77
* Best-case performance O(1)
88
* Average performance O(log n)
99
* Worst-case space complexity O(1)
1010
*/
11-
public final class BinarySearch{
11+
public final class BinarySearch {
1212

1313
/**
1414
* @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
1717
* @return index of the element
1818
*/
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);
2121
}
2222

2323
/**
2424
* @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
2727
* @param right The upper bound
2828
* @return the location of the key
2929
**/
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) {
3131
if (left > right) {
3232
return -1; // Key not found
3333
}
3434

3535
// Find median
36-
int median = (left + right)/2;
36+
int median = left + (right - left) / 2;
3737
int comp = key.compareTo(array[median]);
3838

3939
if (comp < 0) {

0 commit comments

Comments
 (0)