stablePartition<T> function

int stablePartition<T>(
  1. List<T> list,
  2. bool predicate(
    1. T
    )
)

Reorders the elements in the list in such a way that all elements for which the predicate returns true precede the elements for which it returns false.

The relative order of the elements is strictly preserved. Returns the index of the first element of the second group (i.e. returning false).

Example:

final list = [1, 2, 3, 4, 5, 6];
final p = stablePartition(list, (int n) => n % 2 == 0);
// list becomes [2, 4, 6, 1, 3, 5], returns 3

Implementation

int stablePartition<T>(List<T> list, bool Function(T) predicate) {
  var trues = <T>[];
  var falses = <T>[];
  for (var element in list) {
    if (predicate(element)) {
      trues.add(element);
    } else {
      falses.add(element);
    }
  }
  var partitionPoint = trues.length;
  list.clear();
  list.addAll(trues);
  list.addAll(falses);
  return partitionPoint;
}