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. Binary Search
Written by Jonathan Sande

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

Binary search is one of the most efficient searching algorithms with a time complexity of O(log n). You’ve already implemented a binary search once using a binary search tree. In this chapter, you’ll reimplement binary search on a sorted list.

Two conditions need to be met for the type of binary search that this chapter describes:

  • The collection must be sorted.
  • The underlying collection must be able to perform random index lookup in constant time.

As long as the elements are sorted, a Dart List meets both requirements.

Linear Search vs. Binary Search

The benefits of binary search are best illustrated by comparing it with linear search. Dart’s List type uses a linear search to implement its indexOf method. It traverses through the whole collection until it finds the first element:

1 19 150 15 24 5 22 17 105 31
Linear search for the value 31

Binary search handles things differently by taking advantage of the fact that the collection is already sorted. Here’s an example of applying binary search to find the value 31:

1 19 150 15 24 5 22 17 105 31
Binary search for the value 31

Instead of eight steps to find 31, it only takes three. Here’s how it works:

Step 1: Find the Middle Index

The first step is to find the middle index of the collection.

9 13 541 38 47 8 05 25 757 63

Step 2: Check the Element at the Middle Index

The next step is to check the element stored at the middle index. If it matches the value you’re looking for, return the index. Otherwise, continue to Step 3.

Step 3: Split and Repeat

The final step is to cut the list in half and start over. This time, you’ll only consider the elements exclusively to the left or to the right of the middle index, depending on the value you’re searching for. If the value you’re searching for is less than the middle value, you search the left subsequence. If it’s greater than the middle value, you search the right subsequence.

7 92 176 91 6 42 04 416 73 74

Implementation

Open the starter project for this chapter. Create a new lib folder in the root of your project. Then add a new file to it called binary_search.dart.

Adding an Extension on List

Add the following List extension to binary_search.dart:

extension SortedList<E extends Comparable<E>> on List<E> {
  int? binarySearch(E value) {
    // more to come
  }
}

Writing the Algorithm

Next, fill in the logic for binarySearch by replacing // more to come in the code above with the following:

// 1
var start = 0;
var end = length;
// 2
while (start < end) {
  // 3
  final size = end - start;
  final middle = start + size ~/ 2;
  // 4
  if (this[middle] == value) {
    return middle;
  // 5
  } else if (this[middle].compareTo(value) < 0) {
    start = middle + 1;
  } else {
    end = middle;
  }
}
// 6
return null;

Testing it Out

That wraps up the implementation of binary search! Open bin/starter.dart to test it out. Replace the contents of the file with the following:

import 'package:starter/binary_search.dart';

void main() {
  final list = <num>[1, 5, 15, 17, 19, 22, 24, 31, 105, 150];

  final search31 = list.indexOf(31);
  final binarySearch31 = list.binarySearch(31);

  print('indexOf: $search31');
  print('binarySearch: $binarySearch31');
}
indexOf: 7
binarySearch: 7

Challenges

Try out the challenges below to further strengthen your understanding of binary searches. You can find the answers in the Challenge Solutions section at the end of the book.

Challenge 1: Binary Search as a Free Function

In this chapter, you implemented binary search as an extension of List. Since binary search only works on sorted lists, exposing binarySearch for every list (including unsorted ones) opens it up to being misused.

Challenge 2: Recursive Search

Since a sorted list isn’t a tree-like data structure, you didn’t need to use recursion to perform the binary search. But that doesn’t mean you can’t. Just for fun, write binarySearch as a recursive function.

Challenge 3: Searching for a Range

Write a function that searches a sorted list and finds the range of indices for a particular element. You can start by creating a class named Range that holds the start and end indices.

final list = [1, 2, 3, 3, 3, 4, 5, 5];
final range = findRange(list, value: 3);

Key Points

  • Binary search is only a valid algorithm on sorted collections.
  • Binary search guesses the middle value in a list. If it’s wrong, it continues cutting the list in half and guessing the middle value until it finds the value or discovers it doesn’t exist.
  • Sometimes it may be beneficial to sort a collection to leverage the binary search capability for looking up elements.
  • The indexOf method on List uses a linear search with O(n) time complexity. Binary search has O(log n) time complexity, which scales much better for large data sets if you do repeated lookups.
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.
© 2024 Kodeco Inc.

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.

Unlock now