0
0
CsharpProgramBeginner · 2 min read

C# Program for Binary Search with Example and Explanation

A C# program for binary search uses a sorted array and repeatedly divides the search interval in half using while loop and if conditions; for example, int BinarySearch(int[] arr, int target) { int left = 0, right = arr.Length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) return mid; else if (arr[mid] < target) left = mid + 1; else right = mid - 1; } return -1; }.
📋

Examples

Inputarr = [1, 3, 5, 7, 9], target = 5
Output2
Inputarr = [2, 4, 6, 8, 10], target = 7
Output-1
Inputarr = [10, 20, 30, 40, 50], target = 10
Output0
🧠

How to Think About It

To perform a binary search, start with the whole sorted array and find the middle element. Compare the middle element with the target value. If they match, return the middle index. If the target is smaller, repeat the search on the left half; if larger, on the right half. Keep narrowing the search until the target is found or the search space is empty.
📐

Algorithm

1
Set left pointer to the start of the array and right pointer to the end.
2
While left pointer is less than or equal to right pointer:
3
Calculate middle index as the average of left and right pointers.
4
If the middle element equals the target, return the middle index.
5
If the middle element is less than the target, move left pointer to mid + 1.
6
Otherwise, move right pointer to mid - 1.
7
If the target is not found, return -1.
💻

Code

csharp
using System;
class Program {
    static int BinarySearch(int[] arr, int target) {
        int left = 0, right = arr.Length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) return mid;
            else if (arr[mid] < target) left = mid + 1;
            else right = mid - 1;
        }
        return -1;
    }
    static void Main() {
        int[] numbers = {1, 3, 5, 7, 9};
        int target = 5;
        int result = BinarySearch(numbers, target);
        Console.WriteLine(result);
    }
}
Output
2
🔍

Dry Run

Let's trace searching for target 5 in array [1, 3, 5, 7, 9].

1

Initialize pointers

left = 0, right = 4 (array length - 1)

2

Calculate mid

mid = 0 + (4 - 0) / 2 = 2

3

Compare mid element

arr[2] = 5 equals target 5, return 2

leftrightmidarr[mid]action
0425Found target, return 2
💡

Why This Works

Step 1: Divide and conquer

The code splits the array into halves by calculating the middle index with mid = left + (right - left) / 2 to avoid overflow.

Step 2: Compare middle element

It compares the middle element with the target using if statements to decide which half to search next.

Step 3: Adjust search range

If the target is greater, it moves the left pointer to mid + 1, else moves the right pointer to mid - 1, narrowing the search.

Step 4: Return result

If the target is found, it returns the index; if not found after the loop ends, it returns -1.

🔄

Alternative Approaches

Recursive binary search
csharp
using System;
class Program {
    static int BinarySearch(int[] arr, int target, int left, int right) {
        if (left > right) return -1;
        int mid = left + (right - left) / 2;
        if (arr[mid] == target) return mid;
        else if (arr[mid] < target) return BinarySearch(arr, target, mid + 1, right);
        else return BinarySearch(arr, target, left, mid - 1);
    }
    static void Main() {
        int[] numbers = {1, 3, 5, 7, 9};
        int target = 5;
        int result = BinarySearch(numbers, target, 0, numbers.Length - 1);
        Console.WriteLine(result);
    }
}
Uses recursion instead of a loop; easier to read but uses more stack memory.
Using Array.BinarySearch method
csharp
using System;
class Program {
    static void Main() {
        int[] numbers = {1, 3, 5, 7, 9};
        int target = 5;
        int result = Array.BinarySearch(numbers, target);
        Console.WriteLine(result >= 0 ? result : -1);
    }
}
Built-in method is simple and optimized but less educational for learning the algorithm.

Complexity: O(log n) time, O(1) space

Time Complexity

Binary search divides the search space in half each time, so it runs in logarithmic time, O(log n), where n is the number of elements.

Space Complexity

The iterative version uses constant extra space O(1) as it only stores a few variables; recursive version uses O(log n) due to call stack.

Which Approach is Fastest?

The iterative approach is fastest and uses less memory; built-in methods are optimized but hide the logic; recursion is elegant but uses more stack.

ApproachTimeSpaceBest For
Iterative Binary SearchO(log n)O(1)Memory efficient and fast
Recursive Binary SearchO(log n)O(log n)Clear logic but uses stack
Array.BinarySearch MethodO(log n)O(1)Quick use of built-in optimized method
💡
Always ensure the array is sorted before performing binary search to get correct results.
⚠️
Beginners often forget to update the left or right pointers correctly, causing infinite loops or wrong results.