Sub topic 9
Sorting and searching
This chapter covers ordering the elements of a list and finding elements in a collection. It assumes you can read Dart syntax, use generics such as List<int>, and handle nullable types such as int?. It also assumes you know the where, map, and toList methods from the previous chapter, and that you know lists can be growable, fixed-length, or const.
Sorting is a List operation
Only List has a sort method. Set and Map have no meaningful index order to rearrange, and a lazy Iterable returned by where or map has no sort either. To sort those, first copy the elements into a list.
List.sort changes the list in place and returns void. This is the most common beginner mistake: final sorted = nums.sort(); does not compile, because there is no value to assign. To keep the original order, copy first.
void main() {
final nums = [5, 3, 8, 1];
final copy = [...nums]..sort();
print(nums); // [5, 3, 8, 1]
print(copy); // [1, 3, 5, 8]
nums.sort((a, b) => b.compareTo(a));
print(nums); // [8, 5, 3, 1]
}Calling sort() with no argument uses the elements' natural order. This works for int, double, String, and any class that implements Comparable.
How a comparator works
A comparator is a function int Function(E a, E b). It returns:
- a negative number if
ashould come beforeb, - zero if the two are equivalent for ordering purposes,
- a positive number if
ashould come afterb.
Most of the time you do not write the arithmetic yourself. You call compareTo on a field, which returns exactly this kind of result. To reverse the order, swap the operands: b.compareTo(a).
class Person {
final String name;
final int age;
const Person(this.name, this.age);
@override
String toString() => '$name($age)';
}
void main() {
final people = [
Person('Cy', 30),
Person('Ann', 25),
Person('Bo', 30),
Person('Al', 25),
];
people.sort((a, b) {
final byAge = b.age.compareTo(a.age); // oldest first
if (byAge != 0) return byAge;
return a.name.compareTo(b.name); // tie-break by name
});
print(people); // [Bo(30), Cy(30), Al(25), Ann(25)]
}To sort by several keys, compare the first key and return its result unless it is zero. Only then fall through to the next key.
Avoid subtraction comparators
You may see (a, b) => a - b. This works for small integers but has problems:
- With
doublevalues the result is adouble, so it does not match the requiredintreturn type and fails to compile. - With very large integers, subtraction can overflow in some runtimes. For example, Dart compiled to JavaScript uses doubles for numbers.
- It is easy to get the direction wrong.
Use a.compareTo(b) instead.
Strings sort by code unit
String.compareTo compares UTF-16 code units. All uppercase ASCII letters have lower values than all lowercase letters, so 'Cherry' sorts before 'apple'. For case-insensitive ordering, normalize inside the comparator.
void main() {
final words = ['banana', 'apple', 'Cherry'];
words.sort();
print(words); // [Cherry, apple, banana]
words.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
print(words); // [apple, banana, Cherry]
}Code unit order is not the same as dictionary order for human languages. Accented letters, for example, sort after z. Locale-aware sorting needs the intl package, which is outside this chapter.
Making your own class sortable
If a class has one obvious ordering, implement Comparable<T> and define compareTo. Then list.sort() works without a comparator.
class Version implements Comparable<Version> {
final int major;
final int minor;
const Version(this.major, this.minor);
@override
int compareTo(Version other) {
final c = major.compareTo(other.major);
return c != 0 ? c : minor.compareTo(other.minor);
}
@override
String toString() => '$major.$minor';
}
void main() {
final versions = [Version(1, 10), Version(1, 2), Version(0, 9)];
versions.sort();
print(versions); // [0.9, 1.2, 1.10]
}The type system does not check that the element type is Comparable when you call sort() with no argument. If it is not, the call fails at runtime. If a class has several reasonable orderings (by name, by age, by date), skip Comparable and pass a comparator at each call site.
Stability, consistency, and nulls
Three properties of comparators cause bugs that are hard to track down.
- Stability. A stable sort keeps equal elements in their original relative order. Dart's
List.sortdoes not guarantee this. If you need a stable result, either break ties explicitly, as thePersonexample does, or usemergeSortfrompackage:collection, which is stable. - Consistency. A comparator must give the same answer for the same pair every time, and it must be transitive: if
a < bandb < c, thena < c. An inconsistent comparator can produce a wrongly ordered list without any error. - Nulls.
nullhas nocompareTo. For aList<int?>, decide where nulls go and handle them first in the comparator.
void main() {
final scores = <int?>[7, null, 3, null, 9];
scores.sort((a, b) {
if (a == null && b == null) return 0;
if (a == null) return 1; // nulls last
if (b == null) return -1;
return a.compareTo(b);
});
print(scores); // [3, 7, 9, null, null]
}Sorting a Set, a Map, or an Iterable
Because sort belongs to List, convert first. For maps, you usually sort the entries and then rebuild a map if you need one. A map literal built with collection for keeps insertion order, so the rebuilt map stays sorted by value.
void main() {
final stock = {'apple': 3, 'pear': 0, 'plum': 5};
final ranked = stock.entries.toList()
..sort((a, b) => b.value.compareTo(a.value));
for (final e in ranked) {
print('${e.key}: ${e.value}');
}
// plum: 5
// apple: 3
// pear: 0
final byValue = {for (final e in ranked) e.key: e.value};
print(byValue); // {plum: 5, apple: 3, pear: 0}
}If you need a collection that is always sorted by key as you add to it, use SplayTreeMap or SplayTreeSet instead. They are covered in a later chapter.
Searching a list
Dart offers a family of search methods. They differ in what they return when nothing matches, and that difference is what you should choose by.
| Method | Returns | When nothing matches |
|---|---|---|
| `contains(x)` | `bool` | `false` |
| `indexOf(x)`, `lastIndexOf(x)` | `int` | `-1` |
| `indexWhere(test)`, `lastIndexWhere(test)` | `int` | `-1` |
| `firstWhere(test, orElse: ...)` | element | calls `orElse`, or throws `StateError` if none is given |
| `singleWhere(test)` | element | throws `StateError` (also if more than one matches) |
| `firstOrNull`, `lastOrNull`, `singleOrNull` | `E?` | `null` |
| `any(test)`, `every(test)` | `bool` | `false` for `any`, `true` for `every` on an empty collection |
void main() {
final names = ['ann', 'bo', 'cy', 'bo'];
print(names.contains('cy')); // true
print(names.indexOf('bo')); // 1
print(names.lastIndexOf('bo')); // 3
print(names.indexOf('zed')); // -1
print(names.indexWhere((n) => n.startsWith('c'))); // 2
print(names.firstWhere((n) => n.length > 2, orElse: () => 'none')); // ann
print(names.firstWhere((n) => n.length > 5, orElse: () => 'none')); // none
print(names.where((n) => n.length > 5).firstOrNull); // null
try {
names.singleWhere((n) => n == 'bo');
} on StateError {
print('not exactly one match'); // 'bo' appears twice
}
print(names.any((n) => n == 'bo')); // true
print(names.every((n) => n.length < 4)); // true
}firstOrNull and its siblings are available in core Dart from version 3.0. Before that they lived in package:collection. They fit well with the null-aware operators from earlier chapters, for example list.firstOrNull ?? defaultValue.
Two habits prevent most search bugs:
- Do not use the result of
indexOfas an index without checking for-1. Passing-1to[]throws aRangeError. - Prefer
firstOrNullorfirstWherewithorElsewhen a missing element is a normal case. Reserve the throwing forms for situations where a missing element is truly a bug.
Cost: linear scans versus hashing
All the methods above scan the list from the start. That is O(n) time, which is fine for a few hundred elements and wasteful when you repeat the search many times over a large list. The usual remedies:
- If you only ask "is this value present?", keep the values in a
Set.containson aSetis O(1) on average. - If you look up records by an identifier, put them in a
Mapkeyed by that identifier. - If the list is already sorted and you search it repeatedly, use binary search.
Binary search on a sorted list
Binary search repeatedly halves the range it examines, so it takes O(log n) comparisons. It only works if the list is sorted by the same ordering you search with. On an unsorted list it returns wrong answers without any error.
package:collection provides binarySearch and lowerBound. The sketch below shows the idea with no dependencies.
int binarySearchIndex(List<int> sorted, int target) {
var low = 0;
var high = sorted.length - 1;
while (low <= high) {
final mid = low + (high - low) ~/ 2;
final value = sorted[mid];
if (value == target) return mid;
if (value < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
void main() {
final data = [1, 3, 5, 8, 9, 12];
print(binarySearchIndex(data, 8)); // 3
print(binarySearchIndex(data, 4)); // -1
}Sorting costs O(n log n), so sorting just to search once is slower than one linear scan. Sorting pays off when you search many times, or when you also need the data in order for display.
Common errors
- Assigning the result of
sort(). It returnsvoid. Use a cascade, as in[...nums]..sort(). - Sorting a lazy iterable.
nums.where(...).sort()does not exist. CalltoList()first. - Sorting a const or unmodifiable list. Copy it first.
- Forgetting to reverse. For descending order, swap the operands in the comparator rather than calling
reversedon a list you intended to sort in place. - Relying on stable order. Break ties with a second key.
- Using
singleWherewhen duplicates are possible. It throws if more than one element matches.
Exercise
You have final items = <String>['pear', 'Apple', 'fig', 'banana'];. Write the code to produce a new list sorted by length (shortest first), with ties broken alphabetically ignoring case, without changing items.
Show answer
Copy the list, then sort the copy with a two-key comparator:
final sorted = [...items]
..sort((a, b) {
final byLength = a.length.compareTo(b.length);
if (byLength != 0) return byLength;
return a.toLowerCase().compareTo(b.toLowerCase());
});
The result is [fig, pear, Apple, banana]. The copy leaves items unchanged, and the explicit tie-break does not depend on sort stability.
Exercise
A program checks whether each of 100,000 incoming user IDs appears in a list of 50,000 banned IDs. The code calls banned.contains(id) on a List<int>. What is the problem, and what is the simplest fix?
Show answer
Each contains call scans the list, which is O(n), so the total work is about 100,000 × 50,000 comparisons. Build a Set<int> once with final bannedSet = banned.toSet(); and call bannedSet.contains(id), which is O(1) on average. Sorting the list and using binary search would also work, but the Set is simpler because the question is only membership.
Exercise
What does [3, 1, 2].sort() return, and why does const [3, 1, 2].sort() fail at runtime?
Show answer
sort() returns void, because it reorders the list in place and returns nothing. A const list is unmodifiable, so sorting it throws UnsupportedError. Copy it first, for example [...const [3, 1, 2]]..sort().