Add Util.linearSearch
PiperOrigin-RevId: 281037183
This commit is contained in:
parent
734b4ad9c8
commit
82b218607f
@ -713,11 +713,29 @@ public final class Util {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the index of the first occurrence of {@code value} in {@code array}, or {@link
|
||||
* C#INDEX_UNSET} if {@code value} is not contained in {@code array}.
|
||||
*
|
||||
* @param array The array to search.
|
||||
* @param value The value to search for.
|
||||
* @return The index of the first occurrence of value in {@code array}, or {@link C#INDEX_UNSET}
|
||||
* if {@code value} is not contained in {@code array}.
|
||||
*/
|
||||
public static int linearSearch(int[] array, int value) {
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (array[i] == value) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return C.INDEX_UNSET;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the index of the largest element in {@code array} that is less than (or optionally
|
||||
* equal to) a specified {@code value}.
|
||||
* <p>
|
||||
* The search is performed using a binary search algorithm, so the array must be sorted. If the
|
||||
*
|
||||
* <p>The search is performed using a binary search algorithm, so the array must be sorted. If the
|
||||
* array contains multiple elements equal to {@code value} and {@code inclusive} is true, the
|
||||
* index of the first one will be returned.
|
||||
*
|
||||
@ -731,8 +749,8 @@ public final class Util {
|
||||
* @return The index of the largest element in {@code array} that is less than (or optionally
|
||||
* equal to) {@code value}.
|
||||
*/
|
||||
public static int binarySearchFloor(int[] array, int value, boolean inclusive,
|
||||
boolean stayInBounds) {
|
||||
public static int binarySearchFloor(
|
||||
int[] array, int value, boolean inclusive, boolean stayInBounds) {
|
||||
int index = Arrays.binarySearch(array, value);
|
||||
if (index < 0) {
|
||||
index = -(index + 2);
|
||||
|
Loading…
x
Reference in New Issue
Block a user