Site icon DataFlair

Binary Search in C

binary search in c

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:

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.

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:

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:

Limitations of Binary Search in C

Some limitations include:

Time and Space Complexity Analysis

1) Time Complexity

Case Time Complexity
Best Case O(1)
Average Case O(logn)
Worst Case O(logn)

2) Space Complexity: O(1)

Applications of C Binary Search

C Binary search is used extensively in areas like:

It shines when fast lookups are needed in sorted data.

Common Pitfalls

Some common mistakes are:

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.

Exit mobile version