anon? exercises: Binary search -w3resource
w3resource
C Exercises: Binary search
Last update on January 25 2017 11:38:59 (UTC/GMT +8 hours)
C Programming Searching and Sorting Algorithm: Exercise-1 with
Solution
Write a C program for binary search
Note: Binary Search : In computer science, a binary search or half-interval search algorithm finds
the position of a target value within a sorted array. The binary search algorithm can be classified
as a dichotomies divide-and-conquer search algorithm and executes in logarithmic time.
Given a sorted array arra[] of n elements, write a function to search a given element x in arra[]
Test Data:
15
18
20
Expected Output :
15 value found at 0 position
Pictorial presentation - Binary search algorithm :
Number
hpiiwmw wresouree.comve-pragramming-exercises/searching-anc-sortinglo-search-and-sarting-exercisa-t.php 6rranot7 exercises: Binary search -w3resource
Low High Mid Seareh (a5
#10 8 4 earch (45)
mid =
| low + high ]
Mid
38 < 45 ——> Low = Mid + 1=
ms
pn: 216rranot7 C exerelses: Binary search -w3resource
Low High Mid
#1 #0 8 4
#2°=«5 8 6
High = Mid - 1 = 5<— 45 <77
wiresounre.com
Sample Solution :
C Code:
dincludecstaio.n>
void main()
‘
Ant arra[100),i¢n)x,£,Lem, £lag=0;
prints ("Input no, of elements in an arzay\n");
sn;
Input $d value in ascending ordex\n"/n):
ficngite)
"ye
sant ("Sa", 6x) 7
(* Binary Search logic */
E60; 1=n-is
while (fe=1)
‘
ma(£41) /27
if (esrarra(ml)
‘
flag=1;
break:
>
hpiiwmw wresouree.comve-pragramming-exercises/searching-anc-sortinglo-search-and-sarting-exercisa-t.php a6anon? exercises: Binary search -w3resource
(xcarra[n})
£ (flag
printe("d value not found\n",x);
Flowchart :
int axra[LOo}ji.n,
xf.m,flag=0:
——
[printf("input no, of elements in. an array\n");
scanf("%od", en),
lprintf("input %d value in ascending order\n",n),
=O.
printf ("Input the value to be search :"),
scanf("%d" 62%),
scanf("%d"éeacrapiD;
Binary
hpiwmw wresouree.come-pragramming-exercises/searching-anc-sortinglo-search-and-sarting-exercisa-.phpanor? exercises: Binary search -w3resource
m+:
ptintf("%d value || printt("%d value found
not found\a",x); || at Ya position \n" xan):
End
C Code Editor:
wnasere=ay
40-7 3b8343ebe35.c -0 ObF63cae
be3
students@programming-editor:~§ gcc obf63ca0-5*3
@bF63ca0-5#3d-11e7-b040-73b8343ebe35
Input no. of elements in an array
Input 5 value in ascending order
Improve this sample solution and post your code through Disqus.
5#3d-11e7-bede-73
-b040-73b8343et
Join our Question Answer community to learn and share your programming knowledge.
Help the community:
PHP: Loop
JavaScript: Delete duplicates in an array
Oracle: Round the number
hpiiwmw wresouree.comve-pragramming-exercises/searching-anc-sortinglo-search-and-sarting-exercisa-t.php