Binary Search Implementation Using C#

Today we will discuss the Binary Search Algorithm. It is one of the Divide and conquer algorithms types, where in each step, it halves the number of elements it has to search, making the average time complexity to O (log n). It works on a sorted array. Given below are the steps/procedures of the Binary Search algorithm.

  • In each step, it compares the search key with the value of the middle element of the array.

  • The keys matching in step 1 means, a matching element has been found and its index (or position) is returned. Else step 3 or 4.

  • If the search key is less than the middle element, then the algorithm repeats its action on the sub-array to the left of the middle element or,

  • If the search key is greater than the middle element, then the algorithm repeats its action on the sub-array to the right of the middle element.

  • If the search key is not matching any of the subsequent left or right array, then it means that the key is not present in the array and a special "Nil" indication can be returned.

We will first have a look at the C# implementation using an iterative approach.

  1. public static object BinarySearchIterative(int[] inputArray, int key)  
  2.   int min = 0;
      int max = inputArray.Length - 1; 
  3.     while (min <=max)  
  4.     {  
  5.        int mid = (min + max) / 2;  
  6.        if (key == inputArray[mid])  
  7.        {  
  8.             return ++mid;  
  9.        }  
  10.        else if (key < inputArray[mid])  
  11.        {  
  12.            max = mid - 1;  
  13.        }  
  14.        else  
  15.        {  
  16.             min = mid + 1;  
  17.        }  
  18.    }  
  19.    return "Nil";  
  20. }  

And here is the recursive one. Please note that in recursive, you need to pass min as 0 and max as inputArray.Length - 1

  1. public static object BinarySearchRecursive(int [] inputArray, int key, int min, int max)  
  2. {  
  3.       if (min > max)  
  4.       {  
  5.           return "Nil";  
  6.       }  
  7.       else  
  8.       {  
  9.           int mid = (min+max)/2;  
  10.           if (key == inputArray [mid])  
  11.           {  
  12.              return ++mid;  
  13.            }  
  14.            else if (key < inputArray [mid])  
  15.            {  
  16.                return BinarySearchRecursive(inputArray, key, min, mid - 1);  
  17.            }  
  18.            else  
  19.            {  
  20.               return BinarySearchRecursive(inputArray, key, mid + 1, max);  
  21.            }  
  22.       }  
  23.  }  

Ebook Download
View all
Learn
View all