Binary Search in C

Get Certified in C Programming and Take Your Skills to the Next Level

Searching algorithms play a crucial role in the realm of computer science and programming. They allow us to efficiently find an item from a collection of data. Binary search in C is one such algorithm that makes searching extremely fast and efficient.

Binary search in C uses a divide-and-conquer strategy to significantly speed up searching in sorted data as opposed to linear search, which examines each element one at a time. This article will offer a straightforward explanation of binary search along with C code samples for beginners.

When to Apply Binary Search in C?

Binary search in C only works on sorted data sets. The collection must be arranged in ascending or descending order. This sorting enables the divide-and-conquer approach.

C Binary search can be applied to:

  • Sorted arrays
  • Linked lists
  • Binary search trees

If the data is unsorted, the binary search will fail. Linear search is better suited for unsorted data.

How Binary Search in C Works

The binary search in C follows a divide-and-conquer strategy. It continuously divides the search space in half, inspects the middle element, and repeats until the target is found or the search space is exhausted.

The key steps are:

1. Find midpoint index of the entire dataset.
2. Compare element at midpoint against target value.
3. If equal, return index of match.
4. If less, repeat search on left half.
5. If greater, repeat search on right half.

This recursive halving of search space enables tremendous efficiency gains.

binary search in c

Here is a step-by-step example to explain how the binary search algorithm works:

Let’s say we have a sorted array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91} and we want to search for the value 23.

The steps are:

  • Set lower index to 0 and the upper index to n-1. Here, n is the number of elements in the array, which is 10. So lower = 0 and upper = 9 (10-1 = 9)
  • Calculate the mid index as mid = (lower + upper) / 2. In this case, mid = (0 + 9) / 2 = 4.
  • Compare the value at arr[mid] with the target value 23. Here arr[mid] is arr[4], which is 16.
  • Since 16 is less than 23, the target is greater than the mid element. So set lower = mid + 1. This eliminates the left half of the array.
  • Recalculate mid index with new lower and upper bounds. mid = (lower + upper) / 2 = (5 + 9) / 2 = 7
  • Check if arr[mid] (which is 38) equals target. It does not. Since 38 > 23, set upper = mid – 1. This eliminates the right half.
  • Recalculate mid as (lower + upper) / 2 = (5 + 6) / 2 = 5
  • Check arr[mid] (which is 23) against the target 23. It matches!
  • Return the index mid.

So, in summary, we first compared against the middle element to eliminate half the array, then repeated the process, treating the remaining elements as new arrays until the target was found.

Binary Search Algorithm in C

More formally, the binary search algorithm involves:

1. Set lowerIndex = 0, upperIndex = size – 1
2. Compute midpoint index: midIndex = (lowerIndex + upperIndex) / 2
3. If array[midIndex] == target, return midIndex
4. Else if array[midIndex] < target, set lowerIndex = midIndex + 1
5. Else set upperIndex = midIndex – 1
6. Repeat steps 2-5 until target is found or the search space exhausted

Implementing Binary Search in C

Binary search can be implemented iteratively or recursively in C:

1) Iterative Implementation

#include <stdio.h>

int binarySearch(int array[], int n, int target) {
  
  int lowerIndex = 0;
  int upperIndex = n-1;
  
  while(lowerIndex <= upperIndex) {
  
    int midIndex = (lowerIndex + upperIndex) / 2;
    
    if(array[midIndex] == target) {
      return midIndex; 
    }
    
    if(array[midIndex] < target) {
      lowerIndex = midIndex + 1;
    } 
    
    else {
      upperIndex = midIndex - 1;   
    }
    
  }
  
  return -1;
}

int main() {

  int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
  
  int n = sizeof(arr)/sizeof(arr[0]);
  
  int target = 16;
  
  int index = binarySearch(arr, n, target);
  
  if(index != -1) {
    printf("Element found at index %d", index);
  }
  else {
    printf("Element not found");
  }
  
  return 0;
}

Output:

Element found at index 4

2) Recursive Implementation

#include <stdio.h>

int binarySearch(int array[], int lowerIndex, int upperIndex, int target) {

  if (lowerIndex > upperIndex) {
    return -1;
  }

  int midIndex = (lowerIndex + upperIndex) / 2;

  if (array[midIndex] == target) {
    return midIndex;
  }

  if (array[midIndex] < target) {
    return binarySearch(array, midIndex + 1, upperIndex, target); 
  }

  return binarySearch(array, lowerIndex, midIndex - 1, target);

}

int main() {
  
  int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
  int n = sizeof(arr)/sizeof(arr[0]);
  
  int target = 16;
  
  int index = binarySearch(arr, 0, n-1, target);
  
  if(index != -1) {
    printf("Element found at index %d", index);
  }
  else {
    printf("Element not found");
  }

  return 0;
}

Output:

Element found at index 4

The recursive approach is more elegant but can be less efficient due to function call overheads.

Advantages of Binary Search in C

Binary search provides:

  • Faster search in sorted data O(log n) vs O(n) for linear search.
  • Efficient lookup for data stored in arrays, trees, etc.
  • Better performance than linear search for large data sizes.
  • Ability to leverage divide-and-conquer algorithms.

Limitations of Binary Search in C

Some limitations include:

  • Data must be sorted first.
  • Extra memory is needed for recursive implementation.
  • Not easily parallelizable due to data dependencies.

Time and Space Complexity Analysis

1) Time Complexity

CaseTime Complexity
Best CaseO(1)
Average CaseO(logn)
Worst CaseO(logn)

2) Space Complexity: O(1)

Applications of C Binary Search

C Binary search is used extensively in areas like:

  • Database lookup
  • Technical documentation search
  • Data compression
  • Version control systems
  • Low level caches

It shines when fast lookups are needed in sorted data.

Common Pitfalls

Some common mistakes are:

  • Not validating data is sorted first
  • Subtle off-by-one errors in index computation
  • Edge case bugs in loop termination conditions

Carefully testing edge cases and using debug prints can help identify issues.

Conclusion

Binary search in C is an indispensable algorithm for many programming applications. Its divide-and-conquer approach provides logarithmic time lookups in sorted data. While simple in principle, care is needed in implementation to avoid edge case bugs. Overall, binary search in C should be in every coder’s toolkit for writing performant search functionality.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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