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
Kaushik S
Apr 01
2016
Code
777
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
BinarySearch(
int
a[],
int
n,
int
search);
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"
);
for
(
int
i=0;i<n;i++)
{
printf(
"%d\n"
,arr[i]);
}
printf(
"Enter the search element\n"
);
scanf(
"%d"
,&search);
result=BinarySearch(arr,n,search);
if
(result==-1)
{
printf(
"Element not found\n"
);
}
else
{
printf(
"Element Found at position %d\n"
,result);
}
return
0;
}
int
BinarySearch(
int
a[],
int
n,
int
search)
{
int
start=0,mid=0;
int
end=n-1;
while
(start<=end)
{
mid=(start+end)/2;
if
(search==a[mid])
return
mid;
else
if
(search<a[mid])
{
end=mid-1;
}
else
if
(search>a[mid]){
start=mid+1;
}
}
return
-1;
}
Download Link:https://github.com/kaushiks90/SearchingAlogithms
C
Binary Search