c sharp

C# Array Binary Search

A sorted array may be effectively searched for a particular element using the algorithmic approach known as C# array binary search. It employs a divide-and-conquer tactic which constantly splits the array in half and chooses the next search area by comparing the target element with the middle element until the target element is located or the search area is used up; this procedure is repeated. Therefore, to understand the working and functionality of the C# array binary search algorithm, we will explain some C# code examples in this article guide.

Example 1:

We will start from the simplest code example possible to understand the array binary search. The code starts by including the necessary namespace, “System”, to access the “Console” class. It defines a class named “Test”.

Inside the “Test” class, we define a static method named “Main” which is the most necessary part of any code to start and end the execution of a program. Inside the “Main” method, an array of integers named “A” is declared and initialized with a total of 7 values: 2, 5, 8, 11, 12, 15, 18. An integer variable “t” is declared and assigned with a value of 21. This variable represents the target number that we want to search for in the array called “A”.

The code then uses the Array.BinarySearch method of IComparable Interface to perform a binary search on the “A” array to find the index of the target “t” number, i.e. the “A” array and the variable “t” are used as a parameter to the method. The output value is saved in the “i” mutable.

Here comes the conditional statement called the “if-else” statement to perform a check on the “I” variable. When the “I” variable value is higher or equal to 0, it implies that the array includes the desired number. Hence, the “if” part of the statement will be executed. In this case, it prints a message which indicates the index where the number was found via the “Console.WriteLine” function. If the value of the “I” variable is less than 0, it means that the target number was not found in the array.

In this case, the “else” part of the statement is executed and it prints a message stating that the number was not found.

using System;

class Test {

  static void Main() {

   int[] A = { 2, 5, 8, 11, 12, 15, 18 };

   int t = 21;

   int i = Array.BinarySearch(A, t);

   if (i >= 0)
   
      Console.WriteLine("Number found at index: " + i);

   else

      Console.WriteLine("Number not found");

   }

}

Finally, the program ends, and the output is displayed in the following illustration. It displays a message that the number “21” was found or not:

Just like the integer type arrays, we can apply the binarySearch function on the string arrays as well. Therefore, the provided code demonstrates that. We have an array of “A” strings containing some brand names. We want to search for the “LAURAMERCIER” string (regardless of its casing) within the array.

The Array.BinarySearch method is called with the “A” array, the target “t” string, and the “StringComparer.OrdinalIgnoreCase” parameter that ensures that the contrast is made in a case-insensitive means. The index of the value is returned to the method. Otherwise, a negative value is returned. If the returned index of “i” is greater than or equal to zero, it means that the target string was found in the array, and a corresponding message is displayed. Otherwise, if “i” is less than zero, the target string is not found via the “if-else” statement.

using System;

class Test {

  static void Main() {

   string[] A = { "Nars", "hudaBEAUTY", "LAURAmerCIER" };

   string t = "LAURAMERCIER";

   int i = Array.BinarySearch(A, t, StringComparer.OrdinalIgnoreCase);

   if (i >= 0)

      Console.WriteLine("String Value found at index: " + i);

   else

      Console.WriteLine("String Value not found");

   }

}

In this specific code, it outputs the “String Value found at index: 2” statement because the target “LAURAMERCIER” string (in any casing) is present at index 2 in the array:

Example 2:

Let’s have another example of binary search on a sorted array in a different way. The code starts with the same main() method code that we utilized in the previous examples, i.e. the declaration of an integer array “A” and an integer variable “t”. The code calls the BinarySearch method, passing the “A” array and the target value of “t”. It assigns the return value of the method to an integer variable of “I”, i.e. the index of the “t” target. The BinarySearch method takes an integer array of “A” and an integer “t” as parameters. It gives back either a -1 if the element did not exist or an integer which indicates the index of the targeted element in the array.

Inside the BinarySearch method, the “L” variable represents the left boundary of the search range which is initially set to 0 and “R” represents the right boundary which is initially set to the length of the array minus 1. The function goes in a “while” loop that remains in the same situation as long as “L” is less than or equal to “R”. Inside the loop, an integer variable “M” is calculated as the midpoint “index” of the search range using (L + R) / 2.

The code checks if the middle element A[M] is equivalent to the aimed variable “t”. If it’s a match, the method immediately returns the value of “M”. If the central value is smaller than the desired value, it means that the target value should be located in the right half of the search range, i.e. “L” is updated to M + 1 to slim down the exploration range. If the middle element is bigger than the target “t” value, it demonstrates that the “t” value must be situated in the left half of the “A” array, i.e. the right boundary “R” is updated to M – 1.

If the aimed value is not found, the function returns -1. The main() method code then checks if the value of mutable “I” is not equal to -1 which displays the “Value found at index: ” message followed by the index “I”. If the value of “i” is -1, it displays the “Value not found!” message.

using System;
class Program {
    static void Main() {
        int[] A= { 5, 7, 11, 18, 25, 33 };
        int t = 25;
        int i = BinarySearch(A, t);
        if (i != -1)
         Console.WriteLine("Value found at index: " + i);
        else
            Console.WriteLine("Value not found!");
    }
    static int BinarySearch(int[] A, int t) {
        int L = 0;
        int R = A.Length - 1;
        while (L <= R)

        {
            int M = (L + R) / 2;
            if (A[M] == t)
                return M;
            if (A[M] < t)
                L = M + 1;
            else
               R = M - 1;
        }
        return -1; // Element not found

    }

}

The output of this code shows that the value has been found at index “4” of array “A”.

Conclusion

The C# array binary search is a valuable technique when you have a sorted array and you need to locate a specific element efficiently. Particularly for big arrays, the binary search technique is more effective than a linear search since it drastically decreases the number of comparisons which is necessary to discover the target element.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.