WAP for Binary Search in C

Binary search is a fundamental algorithm used in the world of programming to efficiently locate a target value within a sorted array. It operates by repeatedly dividing the search interval in half. In this tutorial, we’ll walk through the process of writing a program for binary search in the C programming language.

WAP for Binary Search in C

Binary Search Algorithm

The binary search algorithm follows these steps

  1. Take a sorted array as input.
  2. Define the search boundaries by setting left and right indices.
  3. Calculate the middle index mid of the array.
  4. Compare the target value with the value at the mid index.
  5. If the target matches the middle element, return the index.
  6. If the target is smaller, update the right index to mid - 1.
  7. If the target is larger, update the left index to mid + 1.
  8. Repeat until the element is found or the search interval becomes empty.

Binary Search Program in C

Let’s write a C program to perform a binary search on a sorted array of integers –


wap for binary search in c

Binary Search C Program Explanation

  • binarySearch function: Performs the binary search by updating the search boundaries and returning the index of the target element.
  • main function: Initializes a sorted array and a target value, calls binarySearch, and displays the result.

See Also

Leave a Comment