From f6cd6a1599fe61637827ec81d7bab736961745d9 Mon Sep 17 00:00:00 2001 From: Electrux Date: Tue, 2 Oct 2018 10:41:25 +0530 Subject: [PATCH] Added binary search using recursion in C --- binary_search/using_recursion.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 binary_search/using_recursion.c diff --git a/binary_search/using_recursion.c b/binary_search/using_recursion.c new file mode 100644 index 00000000..f27ba09e --- /dev/null +++ b/binary_search/using_recursion.c @@ -0,0 +1,33 @@ +#include + +#define MAX 10 + +int arr[ MAX ] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; + +int binarysearch( int begin, int end, int data ) +{ + if( begin > end ) return -1; + + int mid = ( begin + end ) / 2; + + if( arr[ mid ] == data ) return mid; + + if( arr[ mid ] < data ) begin = mid + 1; + else end = mid - 1; + + return binarysearch( begin, end, data ); +} + +int main() +{ + int begin = 0, end = MAX - 1, mid = ( begin + end ) / 2, data, pos; + + printf( "Enter what to search: " ); + scanf( "%d", &data ); + + pos = binarysearch( begin, end, data ); + + if( pos == -1 ) printf( "Element not found in the array.\n" ); + else printf( "Element found in array at position %d.\n", pos + 1 ); + return 0; +}