top of page

Binary Search using C Programming

Writer: compnomicscompnomics

Both linear search and binary search are algorithms used to find an element within a dataset, but they differ in their efficiency and requirements. Here's a breakdown of their key characteristics:


Linear Search:

  • Description: Iterates through each element in the list sequentially until the target element is found or the end of the list is reached.

  • Time Complexity: O(n), which means the search time grows linearly with the size of the dataset (n).

  • Space Complexity: O(1), as it uses constant extra space regardless of the list size.

  • Advantages:

  • Simple to implement.

  • Works with any data structure, including unsorted lists.

  • No pre-processing required.

  • Disadvantages:

  • Can be slow for large datasets.

  • Requires checking every element in the worst case.

Binary Search:

  • Description: Divides the sorted list in half repeatedly, discarding half based on the comparison with the target value, until the target is found or the search space is exhausted.

  • Time Complexity: O(log n), which means the search time grows much slower than linearly with the dataset size.

  • Space Complexity: O(log n), as it uses additional space for storing indices during the recursive process.

  • Advantages:

  • Much faster than linear search for large sorted datasets.

  • Efficiently reduces the search space with each comparison.

  • Disadvantages:

  • Requires the list to be sorted beforehand.

  • More complex to implement than linear search.

Choosing the right algorithm:

  • Use linear search when:

  • The list is small or unsorted.

  • Simplicity is a priority.

  • Use binary search when:

  • The list is large and sorted.

  • Efficiency is important, and speed outweighs the requirement of pre-sorting.


 

Here's a C program demonstrating Binary Search on an array:


#include <stdio.h>

int binary_search(int arr[], int left, int right, int target) {
  while (left <= right) {
    int mid = left + (right - left) / 2; // Avoid integer overflow

    if (arr[mid] == target) {
      return mid; // Element found
    } else if (arr[mid] < target) {
      left = mid + 1; // Search in right half
    } else {
      right = mid - 1; // Search in left half
    }
  }

  return -1; // Element not found
}

int main() {
  int arr[] = {2, 3, 4, 10, 40};
  int size = sizeof(arr) / sizeof(arr[0]);
  int target;

  printf("Enter the value to search: ");
  scanf("%d", &target);

  // Ensure the array is sorted before searching
  if (!is_sorted(arr, size)) {
    printf("Error: Array is not sorted. Binary search requires a sorted array.\n");
    return 1;
  }

  int index = binary_search(arr, 0, size - 1, target);

  if (index != -1) {
    printf("Value found at index %d!\n", index);
  } else {
    printf("Value not found in the array.\n");
  }

  return 0;
}

// Function to check if an array is sorted (optional)
int is_sorted(int arr[], int size) {
  for (int i = 1; i < size; i++) {
    if (arr[i] < arr[i - 1]) {
      return 0; // Not sorted
    }
  }
  return 1; // Sorted
}

This program demonstrates the following:

  1. binary_search function:

  • Takes the array, left and right indices, and target value as arguments.

  • Uses a while loop to repeatedly refine the search space.

  • Calculates the middle index and compares the element at that index with the target.

  • Updates the search space based on the comparison (left half if target is smaller, right half if larger).

  • Returns the index if the target is found, -1 otherwise.

  1. Main function:

  • Defines a sample array.

  • Takes the search value as input.

  • Checks if the array is sorted (optional, but necessary for binary search).

  • Calls the binary_search function.

  • Prints the result (found or not found).



Remember that binary search only works on sorted arrays. Implement the is_sorted function or ensure your array is sorted before using binary search.

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page