Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added binary search using recursion in C #205

Merged
merged 1 commit into from
Oct 2, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions binary_search/using_recursion.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <stdio.h>

#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;
}