C Program for binary search on array using recursion
C Program to perform binary search on array using recursion
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 | #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); } } |
Output :
1 2 3 4 | 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 |