Dart Program to Implement Binary Search

Dart Program to Implement Binary Search

If you are stepping up from basic search techniques, learning binary search in Dart is a great next step. Binary search is a much faster method than linear search, especially when dealing with large, sorted datasets. It works by repeatedly dividing the search interval in half, which makes it an efficient way to find a specific element in an ordered list. Understanding binary search is essential for anyone who wants to build optimized and high-performance applications in Dart.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Binary search is commonly used in programming problems, search features, and real-world applications like finding a word in a dictionary or looking up data in databases. Unlike linear search, which checks every element, binary search quickly narrows down the possibilities. In this article, we will explore multiple ways to implement binary search in Dart, including iterative, recursive, and other practical approaches, giving beginners a full understanding of this fundamental algorithm.

Program 1: Iterative Binary Search

This program demonstrates a simple iterative approach to binary search. It uses a loop to repeatedly divide the list until the target element is found or the search range is empty.

void main() {

  List<int> numbers = [2, 4, 6, 8, 10, 12, 14];
  int target = 10;
  int left = 0;
  int right = numbers.length - 1;
  bool found = false;

  while (left <= right) {

    int mid = (left + right) ~/ 2;

    if (numbers[mid] == target) {

      print("Element $target found at index $mid");
      found = true;
      break;

    } else if (numbers[mid] < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }

  }

  if (!found) {
    print("Element $target not found in the list");
  }

}

In this program, the while loop continues as long as the search range is valid. The middle element is calculated, and based on its comparison with the target, the search range is adjusted. This iterative approach is beginner-friendly and shows how binary search reduces the number of comparisons compared to linear search.

Program 2: Recursive Binary Search

Recursion provides another way to implement binary search. Here, the function calls itself with a smaller search range until it finds the target or the range is invalid.

int binarySearchRecursive(List<int> numbers, int target, int left, int right) {

  if (left > right) return -1;

  int mid = (left + right) ~/ 2;

  if (numbers[mid] == target) return mid;
  if (numbers[mid] < target) return binarySearchRecursive(numbers, target, mid + 1, right);

  return binarySearchRecursive(numbers, target, left, mid - 1);

}

void main() {

  List<int> numbers = [1, 3, 5, 7, 9, 11];
  int target = 7;
  int result = binarySearchRecursive(numbers, target, 0, numbers.length - 1);

  if (result != -1) {
    print("Element $target found at index $result");
  } else {
    print("Element $target not found in the list");
  }

}

This recursive approach teaches beginners how a problem can be solved by dividing it into smaller subproblems. The function keeps narrowing the search range, showing how recursion can replace loops for certain algorithms. It also reinforces understanding of base cases and function calls.

Program 3: Binary Search Using a Function (Iterative Approach)

This program demonstrates how to wrap the iterative binary search logic in a function, making the code reusable and organized.

int binarySearch(List<int> numbers, int target) {

  int left = 0;
  int right = numbers.length - 1;

  while (left <= right) {

    int mid = (left + right) ~/ 2;

    if (numbers[mid] == target) return mid;
    if (numbers[mid] < target) left = mid + 1;
    else right = mid - 1;

  }

  return -1;

}

void main() {

  List<int> numbers = [5, 10, 15, 20, 25];
  int target = 15;
  int result = binarySearch(numbers, target);

  if (result != -1) {
    print("Element $target found at index $result");
  } else {
    print("Element $target not found in the list");
  }

}

Using a function allows you to reuse the binary search logic in different parts of the program without rewriting it. Beginners can see how functions help organize code and simplify problem-solving, especially when dealing with repeated tasks like searching.

Program 4: Binary Search Using Dart’s Built-in indexWhere (With Sorted Check)

Dart provides some built-in methods that can assist in searching. This example shows how to use indexWhere on a sorted list.

void main() {

  List<int> numbers = [2, 4, 6, 8, 10];
  int target = 6;

  numbers.sort(); // Ensure the list is sorted
  int index = numbers.indexWhere((num) => num == target);

  if (index != -1) {
    print("Element $target found at index $index");
  } else {
    print("Element $target not found in the list");
  }

}

While indexWhere doesn’t perform a true binary search, it shows beginners how Dart’s built-in functions can simplify searching tasks. It is useful when working with small to medium datasets while still highlighting the importance of sorted data for binary search logic.

Program 5: Binary Search in a Large Dataset

This program demonstrates binary search on a larger list, showing how efficiently the algorithm performs even with many elements.

void main() {

  List<int> numbers = List.generate(100, (index) => index * 2); // 0, 2, 4, ..., 198
  int target = 78;
  int left = 0;
  int right = numbers.length - 1;
  bool found = false;

  while (left <= right) {

    int mid = (left + right) ~/ 2;

    if (numbers[mid] == target) {

      print("Element $target found at index $mid");
      found = true;
      break;

    } else if (numbers[mid] < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }

  }

  if (!found) {
    print("Element $target not found in the list");
  }

}

This example shows how binary search can efficiently handle large datasets. Even with 100 or more elements, the algorithm quickly narrows down the search, making it a practical choice for performance-critical applications. Beginners can see the real advantage of binary search over linear search in large lists.

Frequently Asked Questions (FAQ)

Binary search is very efficient but can raise some questions for beginners. Here are the most common ones with simple explanations.

Q1: What is binary search used for?
Binary search is used to find a specific element in a sorted list efficiently. It is widely applied in search features, algorithms, and database queries.

Q2: Does binary search work on unsorted data?
No, binary search requires a sorted list. If the data is unsorted, the results will be incorrect.

Q3: Is binary search faster than linear search?
Yes, binary search is much faster on large datasets because it divides the search space in half with each step.

Q4: Can recursion replace iteration in binary search?
Yes, recursive binary search performs the same steps as iterative binary search, but uses function calls to narrow the search range.

Q5: Why is binary search important for beginners?
Binary search teaches algorithmic thinking, efficiency, and how to optimize searches, which are crucial skills for programming and software development.

Conclusion

Binary search is a fundamental algorithm that every beginner programmer should understand. By implementing it in Dart using iterative, recursive, functional, and built-in approaches, you gain practical skills for searching efficiently. Each method has its own advantages, whether it’s clarity, reusability, or speed.

Practicing these programs helps you understand sorted lists, control structures, and algorithmic thinking. Start with simple iterative solutions, explore recursion, and experiment with Dart’s built-in features. The more you practice, the stronger your foundation will be for advanced algorithms and real-world applications where fast searching is essential.

Scroll to Top