Chapters

Hide chapters

Data Structures & Algorithms in Dart

Second Edition · Flutter · Dart 3.0 · VS Code 1.78

Section VI: Challenge Solutions

Section 6: 21 chapters
Show chapters Hide chapters

13. Chapter 13 Solutions
Written by Jonathan Sande

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Solution to Challenge 1

In this challenge, you implement binary search as a free function. Here’s what it looks like:

int? binarySearch<E extends Comparable<E>>(List<E> list, E value) {
  var start = 0;
  var end = list.length;
  while (start < end) {
    final size = end - start;
    final middle = start + size ~/ 2;
    if (list[middle] == value) {
      return middle;
    } else if (list[middle].compareTo(value) < 0) {
      start = middle + 1;
    } else {
      end = middle;
    }
  }
  return null;
}

The only major difference from the extension that you made earlier is that now you also need to pass the list in as a parameter.

Don’t forget that you need to specify the function’s generic type as num:

final list = [1, 5, 15, 17, 19, 22, 24, 31, 105, 150];
final index = binarySearch<num>(list, 31);
print('Found at index $index'); // 7

Solution to Challenge 2

Here’s how you would implement binarySearch as a recursive function:

Solution to Challenge 3

First, create a class to hold the start and end indices:

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now