bisectRight method

int bisectRight (
  1. E element,
  2. {int compare(
    1. E,
    2. E
    ),
  3. int low,
  4. int high}
)

Returns the index where an element should be inserted in a list, assuming the list is sorted by a compare function.

If this element is already in this list,returns the rightmost index where it can be inserted.

The compare function must act as a Comparator.

The default implementation uses Comparable.compare if compare is omitted.

Two optional parameters low (0 by default) and high (list.length by default) can be provided to bisect only an slice of this list where the element will be inserted.

Implementation

int bisectRight(E element, {int Function(E, E) compare, int low, int high}) {
  compare ??= Comparable.compare as Function(E, E);
  low ??= 0;
  high ??= length;

  if (low < 0) {
    throw ArgumentError('low must be non-negative');
  }

  // This algorithm is very similar to a binary search.
  while (low < high) {
    // At each iteration the algorithm looks at a slice of this list
    // where the element can be inserted, and divides it in half.
    var mid = (low + high) ~/ 2;

    // Then the algorithm compares the element to be inserted to
    // the middle element.
    if (compare(element, this[mid]) < 0) {
      // If the element to be inserted is smaller than the middle
      // element, then in the next iteration we only need to look
      // between the start of the current slice and the middle element.
      high = mid;
    } else {
      // Otherwise the algorithm will look between the element next
      // to the middle one and the end of the current slice.
      low = mid + 1;
    }
  }

  return low;
}