-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
UpperBound.java
33 lines (30 loc) · 961 Bytes
/
UpperBound.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.jwetherell.algorithms.search;
/**
* Upper bound search algorithm.<br>
* Upper bound is kind of binary search algorithm but:<br>
* -It returns index of first element which is grater than searched value.<br>
* -If searched element is bigger than any array element function returns first index after last element.<br>
* <br>
* Behaviour for unsorted arrays is unspecified.
* <p>
* Complexity O(log n).
* <br>
* @author Bartlomiej Drozd <[email protected]>
* @author Justin Wetherell <[email protected]>
*/
public class UpperBound {
private UpperBound() { }
public static int upperBound(int[] array, int length, int value) {
int low = 0;
int high = length;
while (low < high) {
final int mid = (low + high) / 2;
if (value >= array[mid]) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
}