binarySearch<T extends Comparable<T>> function

int binarySearch<T extends Comparable<T>>(
  1. List<T?> sortedList,
  2. T? value, {
  3. int start = 0,
  4. int? end,
  5. int compare(
    1. T,
    2. T
    )?,
})

Implementation

int binarySearch<T extends Comparable<T>>(List<T?> sortedList, T? value,
    {int start = 0, int? end, int Function(T, T)? compare}) {
  compare ??= Comparable.compare;
  var min = 0;
  var max = end ?? sortedList.length;
  while (min < max) {
    var mid = min + ((max - min) >> 1);
    var element = sortedList[mid];
    if (element == null || value == null) {
      if (element == null && value == null) {
        return mid; // Found the position of null
      } else if (element == null) {
        max = mid; // Nulls are considered greater than non-nulls
        continue;
      } else { // if (value == null)
        return -1; // Null cannot be compared, so not found
      }
    }
    var comp = compare(element, value);
    if (comp == 0) return mid;
    if (comp < 0) {
      min = mid + 1;
    } else {
      max = mid;
    }
  }
  return -1;
}