C# Corner
Tech
News
Videos
Forums
Trainings
Books
Events
More
Interviews
Jobs
Live
Learn
Career
Members
Blogs
Challenges
Certifications
Bounties
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Binary Search
WhatsApp
Kaushik S
Apr 01
2016
810
0
0
//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
Binary Search
C
Up Next
Binary Search