binarySearchWithComparator method

int binarySearchWithComparator({
  1. required E element,
  2. required Comparator<E> comparator,
  3. int? fromIndex,
  4. 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 specified comparator, otherwise the result is undefined.

Implementation

int binarySearchWithComparator({
  required E element,
  required Comparator<E> comparator,
  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 = comparator(midVal, element);

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

  return -(low + 1);
}