-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathBinary-Search-code.c
61 lines (45 loc) · 944 Bytes
/
Binary-Search-code.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
54
55
56
57
58
59
60
61
#include <stdio.h>
#include <stdlib.h>
// Creating recursive function for binary search
int binarysearch(int *a, int start, int end, int key)
{
// checking condition
if (start > end)
return -1;
int mid = (start + end) / 2;
if (a[mid] == key)
{
return mid;
}
else if (a[mid] > key)
{
return binarysearch(a, start, mid - 1, key);
}
else
{
return binarysearch(a, mid + 1, end, key);
}
}
// Main Function
void main()
{
int *arr, i, key, n;
printf("Enter number of elements:");
scanf("%d", &n);
arr = (int *)calloc(n, sizeof(int));
for ( i = 0; i < n; i++)
{
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
// Key to be found
printf("Enter key to find:");
scanf("%d", &key);
// Calling Function
int pos = binarysearch(arr, 0, n, key);
// Checking Condition
if (pos != -1)
printf("Element found at: %d", pos + 1);
else
printf("Element not found");
}