D
DSA in DartMedium30 XP3 min read

How do you implement binary search in Dart?

TL;DR: Binary search on a sorted list runs in O(log n). Dart's collection package provides binarySearch(). Implement it manually: mid = (low + high) ~/ 2, compare, narrow range until found or exhausted.

Full Answer

Binary search requires a sorted list. It eliminates half the remaining elements on each comparison, making it O(log n) vs linear search's O(n).

Conditions

  • List must be sorted in the same order as your comparator
  • Returns the index if found, or -1 (manually) / negative insertion point (binarySearch package)
  • Use ~/ for integer division (not / which returns double in Dart)

Code Examples

dartBinary search implementation
Output
3
-1

Common Mistakes

  • Using (low + high) / 2 in integer arithmetic — causes double, use ~/
  • Applying binary search to an unsorted list — results are undefined

Interview Tip

💡

The ~/ operator is Dart-specific. Show it confidently — it demonstrates Dart familiarity. Also explain when binary search is worth the sorted prerequisite cost.

#binary-search#sorted-list#o-log-n#algorithm