TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Binary Search using Recursion
Kaushik S
Apr 03
2016
Code
747
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
//Binary Search
//Time Complexity
//Best Case O(1)
//Worst Case O(logn)
#include <stdio.h>
#include <conio.h>
int
BinarySearchUsingRecursion(
int
a[],
int
n,
int
search,
int
start,
int
end);
int
main()
{
printf(
"Binary Search\n"
);
int
arr[100],n,search,result=0;
printf(
"Enter the number of elements in the array\n"
);
scanf(
"%d"
,&n);
printf(
"Enter the array elements in Ascending order"
);
for
(
int
i=0;i<n;i++)
{
scanf(
"%d"
,&arr[i]);
}
printf(
"The entered array elements are\n"
);
for
(
int
i=0;i<n;i++)
{
printf(
"%d\n"
,arr[i]);
}
printf(
"Enter the search element\n"
);
scanf(
"%d"
,&search);
result= BinarySearchUsingRecursion( arr, n,search,0,n-1);
if
(result==-1)
{
printf(
"Element not found\n"
);
}
else
{
printf(
"Element Found at position %d\n"
,result);
}
return
0;
}
int
BinarySearchUsingRecursion(
int
a[],
int
n,
int
search,
int
start,
int
end)
{
int
mid=0;
if
(start>end)
{
return
-1;
}
mid=(start+end)/2;
if
(search==a[mid])
return
mid+1;
else
if
(search<a[mid])
{
return
BinarySearchUsingRecursion( a, n,search,start,mid-1);
}
else
if
(search>a[mid]){
return
BinarySearchUsingRecursion( a, n,search,mid+1,end);
}
return
-1;
}
C
Binary Search