-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary.c
53 lines (39 loc) · 974 Bytes
/
binary.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <conio.h>
int binarySearch(int a[], int low, int high, int value) {
int mid = (high + low) / 2;
if (a[mid] == value) {
return mid;
}
if (value < a[mid]) {
return binarySearch(a, low, mid, value);
}
if (value > a[mid]) {
return binarySearch(a, mid + 1, high, value);
}
// return -1;
}
void main()
{
int a[20];
int i, result, n, s;
printf("How many elements you want to enter: \n");
scanf("%d", &n);
printf("Enter the elements: \n");
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("\nEnter the element to be searched: ");
scanf("%d", &s);
result = binarySearch(a, 0, n - 1, s);
if (result == -1)
{
printf("\n%d not found in the given array", s);
}
else
{
printf("\n%d is found at position %d", s, result + 1);
}
getch();
}