D
DSA in DartMedium30 XP4 min read

What sorting algorithms does Dart use and how do you sort custom objects?

TL;DR: Dart's List.sort() uses Timsort — O(n log n) average/worst, O(n) best (nearly sorted). Sort custom objects by implementing Comparable<T> or passing a Comparator function. Use sortedBy from package:collection for immutable sorted copies.

Full Answer

Dart's built-in sort is an optimized Timsort — a hybrid merge/insertion sort that's particularly fast on real-world data which is often partially sorted.

Two approaches

  • Implement Comparable<T>: define compareTo() on your class — natural ordering built into the type
  • Pass a Comparator: list.sort((a, b) => a.age.compareTo(b.age)) — ad-hoc sorting without modifying the class
🎯

package:collection's sortedBy and sortedByCompare return new sorted lists without mutating the original. Essential for pure functional data processing.

Code Examples

dartSorting custom objects
Output
[Dart SDK ($0.0, ⭐5), Widget Pro ($29.99, ⭐4), Flutter Book ($39.99, ⭐3)]
Dart SDK ($0.0, ⭐5)
Dart SDK ($0.0, ⭐5)

Common Mistakes

  • Sorting in place when you need the original order — always spread first: [...list]..sort(...)
  • Returning 0 from compareTo when objects aren't actually equal — breaks sort stability

Interview Tip

💡

Multi-key sorting (sort by field A, then B as tiebreaker) is common in interview questions. Show the comparator chaining pattern: if (cmp != 0) return cmp; return b.compareTo(...).

#sorting#comparator#comparable#timsort