D
DSA in DartEasy20 XP3 min read

How do you sort collections in Dart?

TL;DR: List.sort() sorts in-place using a Comparator<T> function. Implement Comparable<T> on a class to make it naturally sortable. Dart uses a hybrid of insertion sort and merge sort (TimSort) — O(n log n).

Full Answer

Dart's List.sort() is an in-place unstable sort. For immutable sorted copies, use [...list]..sort() or list.sorted() (collection package).

Comparator Return Values

  • Negative: a comes before b
  • Zero: a and b are equal
  • Positive: a comes after b
🎯

a.compareTo(b) returns the right values for Comparable types (int, double, String, DateTime). For reverse, use b.compareTo(a).

Code Examples

dartSorting with custom Comparator
Output
// Multi-field sort: difficulty first, title as tiebreaker
// Comparable: questions.sort() with no comparator

Common Mistakes

  • Sorting the original list when you need the original order preserved — always sort a copy
  • Using (a, b) => a.value > b.value ? 1 : -1 — misses the 0 (equal) case and can cause incorrect ordering

Interview Tip

💡

Mention that Dart's sort is not stable (equal elements may reorder). For stable sort, use sortedBy() from the collection package or pad the key to be unique.

#sort#comparator#comparable#sort-algorithm