forked from coder2hacker/Explore-open-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Search.c
66 lines (55 loc) · 1.46 KB
/
Binary_Search.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
62
63
64
65
66
#include <stdio.h>
// Recursive implementation of the binary search algorithm to return
// the position of target `x` in subarray `A[low…high]`
int binarySearch(int A[], int low, int high, int x)
{
// Base condition (search space is exhausted)
if (low > high)
{
return -1;
}
// find the mid-value in the search space and
// compares it with the target
int mid = (low + high)/2; // overflow can happen
// int mid = low + (high - low)/2;
// Base condition (target value is found)
if (x == A[mid])
{
return mid;
}
// discard all elements in the right search space,
// including the middle element
else if (x < A[mid])
{
return binarySearch(A, low, mid - 1, x);
}
// discard all elements in the left search space,
// including the middle element
else
{
return binarySearch(A, mid + 1, high, x);
}
}
int main(void)
{
int A[20],i,num;
printf("\nEnter the range of the array:");
scanf("%d",&num);
printf("\nEnter %d number of elements:",num);
for(i=0;i<=num;i++)
{
scanf("%d",&A[i]);
}
int n = sizeof(A)/sizeof(A[0]);
int low = 0, high = n - 1;
int index = binarySearch(A, low, high, target);
if (index != -1)
{
printf("Element found at index %d", index);
}
else
{
printf("Element not found in the array");
}
return 0;
}