Sorting in Dart

In Dart, we can use the sort method from the dart:core library to sort lists. Let’s look at sorting for built-in types first.

import 'dart:core';

void main() {
  // Sorting functions work for any comparable type in Dart.
  // For a list of comparable types, see the Comparable interface.

  var strs = ['c', 'a', 'b'];
  strs.sort();
  print('Strings: $strs');

  // An example of sorting integers.
  var ints = [7, 2, 4];
  ints.sort();
  print('Ints:    $ints');

  // We can also check if a list is already in sorted order.
  bool s = isSorted(ints);
  print('Sorted:  $s');
}

// Helper function to check if a list is sorted
bool isSorted(List list) {
  for (int i = 1; i < list.length; i++) {
    if (list[i - 1].compareTo(list[i]) > 0) {
      return false;
    }
  }
  return true;
}

To run the program:

$ dart run sorting.dart
Strings: [a, b, c]
Ints:    [2, 4, 7]
Sorted:  true

In this Dart example, we use the sort method which is available on all List objects. This method sorts the list in-place using a comparison sort algorithm.

For checking if a list is sorted, we implement a simple isSorted function, as Dart doesn’t provide a built-in method for this. This function iterates through the list, comparing each element with the next one.

Note that in Dart, the sort method works on any list where the elements implement the Comparable interface. This includes built-in types like String and int, as well as custom classes that implement Comparable.