Write C code to implement the Binary Search algorithm

Binary search is used to quickly find a value in a sorted sequence.At each step, the algorithm compares the median value in the search space to the target value. Based on the comparison and because the sequence is sorted, it can then eliminate half of the search space. By doing this repeatedly, it will eventually be left with a search space consisting of a single element, the target value.

binary search algorithm

In the example given above, we are searching “cat” in sorted array. In each step, algorithm is eliminating half of the elements.

int binarySearch(int arr[],int size, int item)
{
   int left, right, middle;
   left  = 0;
   right = size-1;

   while(left<=right)
   {
      middle = ((left + right)/2);

      if(item == arr[middle])
      {
        return(middle);
      }
      
      if(item > arr[middle])
      {
        left  = middle+1;
      }
      else
      {
        right = middle-1;
      }
   }

   return(-1);
}

Note: This algorithm will not work on an unsorted array.

Complexity:

  • Worst case performance O(log n)
  • Best case performance O(1)
  • Average case performance O(log n)
  • Worst case space complexity O(1)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation