In this program, we are going to share a c program for binary search on array using recursion. If you are a beginner and want to start learning the C programming, then keep your close attention in this tutorial as I am going to share a C program for binary search on an array using recursion with the output.
Copy the below C program and execute it with the help of Turbo C compiler. At the end of this program, We have shared the output of this program.
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 43 44 45 46 47 48 49 50 51 52 |
#include<stdio.h> #include<stdlib.h> #define size 10 int binsearch(int[], int, int, int); int main() { int num, i, key, position; int low, high, list[size]; printf("\nEnter the total number of elements"); scanf("%d", &num); printf("\nEnter the elements of list :"); for (i = 0; i < num; i++) { scanf("%d", &list[i]); } low = 0; high = num - 1; printf("\nEnter element to be searched : "); scanf("%d", &key); position = binsearch(list, key, low, high); if (position != -1) { printf("\nNumber present at %d", (position + 1)); } else printf("\n The number is not present in the list"); return (0); } // Binary Search function int binsearch(int a[], int x, int low, int high) { int mid; if (low > high) return -1; mid = (low + high) / 2; if (x == a[mid]) { return (mid); } else if (x < a[mid]) { binsearch(a, x, low, mid - 1); } else { binsearch(a, x, mid + 1, high); } } |
Enter the total number of elements : 5
Enter the elements of list : 11 22 33 44 55
Enter element to be searched : 33
Number present at 3
Liked this program? Do Like & share with your friends.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: binary search in c, binary search using recursion, binary search using recursion algorithm, binary search without recursion in c, c programs with output, c programs with solutions, implement binary search algorithm without using recursion in c, linear search using recursion in c, list of important c programs