linearSearch<E> function
Returns the first index of the value in the list, otherwise -1.
You can control the range to search using the start and count parameters.
- If
startis given, search start there and go towards the end of thelist. - If
startis not below the length of thelist, -1 will be returned. - If
startis negative, search starts atstart+countor 0, whichever is greater. - If the
countparameter is given, it will check up tocountnumbers of items. - If
countis negative, -1 will be returned.
Complexity: Time O(n) | Space O(1)
Implementation
int linearSearch<E>(
List<E> list,
E value, {
int? start,
int? count,
}) {
int l, h;
int n = list.length;
// determine range [l, h)
l = start ?? 0;
h = n;
if (count != null) {
if (count < 0) return -1;
h = l + count;
if (h > n) h = n;
}
if (l < 0) l = 0;
// forward loop in range [l, h)
for (; l < h; ++l) {
if (list[l] == value) {
return l;
}
}
return -1;
}