linearSearchReversedBy<E> function

int linearSearchReversedBy<E>(
  1. List<E> list,
  2. EqualityTest<E> test, {
  3. int? start,
  4. int? count,
})

Returns the last index where the test is true in the list, otherwise -1.

You can control the range to search using the start and count parameters.

  • If start parameter is not null, search start there and go backwards down to 0.
  • If start is not less than the length of the list, it will start at the end.
  • If the count parameter is given, it will check up to count numbers of items.
  • If either start or count is negative, -1 will be returned.

Complexity: Time O(n) | Space O(1)

Implementation

int linearSearchReversedBy<E>(
  List<E> list,
  EqualityTest<E> test, {
  int? start,
  int? count,
}) {
  int l, h;
  int n = list.length;

  // determine range [l, h)
  l = 0;
  h = start ?? n - 1;
  if (count != null) {
    if (count < 0) return -1;
    l = h - count + 1;
    if (l < 0) l = 0;
  }
  if (h >= n) h = n - 1;

  // reverse loop in range [l, h)
  for (; h >= l; h--) {
    if (test(list[h])) {
      return h;
    }
  }

  return -1;
}