binarySearch method

int binarySearch({
  1. E? element,
  2. int? fromIndex,
  3. int? toIndex,
})

Searches this List or its range for the provided element using the binary search algorithm. The List is expected to be sorted into ascending order according to the Comparable natural ordering of its elements, otherwise the result is undefined.

Implementation

int binarySearch({
  E? element,
  int? fromIndex,
  int? toIndex,
}) {
  fromIndex ??= 0;
  toIndex ??= length;

  rangeCheck(length: length, fromIndex: fromIndex, toIndex: toIndex);

  var low = fromIndex;
  var high = toIndex - 1;

  while (low <= high) {
    // todo: Change to `>>>` operator
    // Change when stable `Dart` SDK version becomes to 2.14.0 over.
    final mid = (low + high) ~/ 2;
    final midVal = this[mid];
    final cmp = element == null ? 1 : midVal.compareTo(element);

    if (cmp < 0) {
      low = mid + 1;
    } else if (cmp > 0) {
      high = mid - 1;
    } else {
      return mid;
    }
  }

  return -(low + 1);
}