In this tutorial you will learn about the C Program to Implement Binary Search and its application with practical example.
C Program to Implement Binary Search
In this tutorial, we will learn to create a C program that will do Implement Binary Search using C programming.
Prerequisites
Before proceeding with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- Conditional statement in C Programming.
- Creating and Using the user-defined function in C programming.
Implement Binary Search
In every programming language, the sorting of data is a very important factor. Sorting works are done mainly with the techniques available in C Language. Many different techniques for sorting are available to work.
But the data structure work is incomplete without the searching of the data. In today’s tutorial, we will implement the binary search in the array to find the element in the array.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declare the variables for the program. 2. Taking the input array in sorte format. 3. Implement the binary search for the element. 4. Print the Result. 5. End the program. |
Program to Implement Binary Search
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
// C program to implement Binary Search #include <stdio.h> // A binary search function. It returns // location of x in given arrayay ary[l..r] is present, // otherwise -1 int binarySearch(int ary[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at the middle // itself if (ary[mid] == x) return mid; // If element is smaller than mid, then // it can only be present in left subarrayay if (ary[mid] > x) return binarySearch(ary, l, mid - 1, x); // Else the element can only be present // in right subarray return binarySearch(ary, mid + 1, r, x); } // We reach here when element is not // present in array return -1; } int main(void) { int ary[] = { 2, 3, 4, 10, 40 }; int n = sizeof(ary) / sizeof(ary[0]); int x = 10; int result = binarySearch(ary, 0, n - 1, x); (result == -1) ? printf("Element is not present in aryay") : printf("Element is present at index %d", result); return 0; } |
Output:-
In the above program, we have first declared and initialized a set of variables required in the program.
- n = it will hold the size of an array.
- ary[]= it will hold the elements in an array.
After this, we make the user-defined function for searching.
Printing the output.