Commit 35d9bdea by aquilescanta Committed by Oliver Woodman

Add Util.linearSearch

PiperOrigin-RevId: 281037183
parent 07bfab8e
...@@ -714,10 +714,28 @@ public final class Util { ...@@ -714,10 +714,28 @@ public final class Util {
} }
/** /**
* 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 * Returns the index of the largest element in {@code array} that is less than (or optionally
* equal to) a specified {@code value}. * 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 * array contains multiple elements equal to {@code value} and {@code inclusive} is true, the
* index of the first one will be returned. * index of the first one will be returned.
* *
...@@ -731,8 +749,8 @@ public final class Util { ...@@ -731,8 +749,8 @@ public final class Util {
* @return The index of the largest element in {@code array} that is less than (or optionally * @return The index of the largest element in {@code array} that is less than (or optionally
* equal to) {@code value}. * equal to) {@code value}.
*/ */
public static int binarySearchFloor(int[] array, int value, boolean inclusive, public static int binarySearchFloor(
boolean stayInBounds) { int[] array, int value, boolean inclusive, boolean stayInBounds) {
int index = Arrays.binarySearch(array, value); int index = Arrays.binarySearch(array, value);
if (index < 0) { if (index < 0) {
index = -(index + 2); index = -(index + 2);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment