binarySearch method

int binarySearch(
  1. List<T> list,
  2. T value, {
  3. int? start,
  4. int? end,
})

Performs a binary search of value on the sorted list. Returns the index of any element that compares equal, or -1 if the value is not found. The result is undefined if the list is not sorted.

By default the whole list is searched, but if start and/or end are supplied, only that range is searched.

Implementation

int binarySearch(List<T> list, T value, {int? start, int? end}) {
  var min = start ??= 0;
  var max = end ??= list.length;
  while (min < max) {
    final mid = min + ((max - min) >> 1);
    final comp = this(list[mid], value);
    if (comp == 0) {
      assert(start <= mid && mid <= end,
          'Index $mid not in inclusive range $start..$end');
      return mid;
    } else if (comp < 0) {
      min = mid + 1;
    } else {
      max = mid;
    }
  }
  return -1;
}