C#  

How to Implement a Binary Search Algorithm in C# With Example

Introduction

When working with large datasets, searching for a specific value efficiently becomes very important. A simple linear search checks each element one by one, which can be slow for large arrays.

This is where Binary Search comes in.

Binary Search is a fast and efficient searching algorithm that works on sorted data. It reduces the search space by half on each step, making it much faster than linear search.

In this article, you will learn how Binary Search works, how to implement it in C#, and how to use it in real-world scenarios using simple and clear examples.

What is Binary Search?

Binary Search is an algorithm used to find a target value in a sorted array by repeatedly dividing the search range into half.

πŸ‘‰ Key Requirement:

  • The array must be sorted (ascending or descending)

How Binary Search Works

Let’s understand the concept step by step.

Example array:

int[] numbers = { 1, 3, 5, 7, 9, 11, 13 };

Suppose we want to find the number 7.

Steps:

  1. Find the middle element

  2. Compare it with the target value

  3. If equal β†’ return index

  4. If target is smaller β†’ search left half

  5. If target is greater β†’ search right half

This process continues until the value is found or the search space becomes empty.

Time Complexity

  • Best Case: O(1)

  • Average Case: O(log n)

  • Worst Case: O(log n)

πŸ‘‰ This makes Binary Search very efficient for large datasets.

Binary Search Implementation in C# (Iterative Approach)

using System;

class Program
{
    static int BinarySearch(int[] arr, int target)
    {
        int left = 0;
        int right = arr.Length - 1;

        while (left <= right)
        {
            int mid = left + (right - left) / 2;

            if (arr[mid] == target)
                return mid;

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

        return -1; // Not found
    }

    static void Main()
    {
        int[] numbers = { 1, 3, 5, 7, 9, 11, 13 };
        int target = 7;

        int result = BinarySearch(numbers, target);

        if (result != -1)
            Console.WriteLine($"Element found at index: {result}");
        else
            Console.WriteLine("Element not found");
    }
}

Explanation of Code

  • left β†’ starting index

  • right β†’ ending index

  • mid β†’ middle element

  • Loop continues until search space is valid

  • Returns index if found, otherwise -1

Binary Search Using Recursion in C#

static int BinarySearchRecursive(int[] arr, int left, int right, int target)
{
    if (left > right)
        return -1;

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

    if (arr[mid] == target)
        return mid;

    if (arr[mid] > target)
        return BinarySearchRecursive(arr, left, mid - 1, target);

    return BinarySearchRecursive(arr, mid + 1, right, target);
}

When Should You Use Binary Search?

  • When data is sorted

  • When performance matters

  • When working with large datasets

Real-World Examples of Binary Search

  1. Searching in a database index

Databases use binary search-like techniques to quickly find records.

  1. Searching contacts in a phone book

Instead of checking each name, you divide the list.

  1. Finding values in sorted arrays

Used in backend systems, APIs, and search features.

Important Tips

  1. Always sort the array before using Binary Search

Array.Sort(numbers);
  1. Avoid integer overflow

Use:

int mid = left + (right - left) / 2;
  1. Check edge cases

  • Empty array

  • Single element

Common Mistakes

  • Using binary search on unsorted data

  • Incorrect mid calculation

  • Infinite loops due to wrong conditions

Built-in Binary Search in C#

C# also provides a built-in method:

int index = Array.BinarySearch(numbers, target);

πŸ‘‰ This is optimized and recommended for simple use cases.

Binary Search vs Linear Search

FeatureBinary SearchLinear Search
RequirementSorted dataNo sorting
Time ComplexityO(log n)O(n)
PerformanceFastSlow

Conclusion

Binary Search is one of the most efficient algorithms for searching in sorted data. By reducing the search space in half at each step, it significantly improves performance compared to linear search.

By learning both iterative and recursive approaches in C#, you can confidently apply binary search in real-world applications like databases, APIs, and large-scale systems.

Start practicing with small arrays, and then move to larger datasets to fully understand its power and efficiency.