-
Notifications
You must be signed in to change notification settings - Fork 253
/
binarysearch.c
61 lines (30 loc) · 876 Bytes
/
binarysearch.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>
/*
Time Complexity : O(logN)
Space Complexity : O(1)
*/
int binarySearch(int a[], int n, int target) { // function to find element
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] < target) {
low = mid + 1;
} else if (a[mid] == target) {
return mid;
} else { // a[mid] > target
high = mid - 1;
}
}
return -1; // if target element not found in array
}
int main() {
int n = 5, found = -1, target = 6;
int a[] = {1, 2, 3, 4, 5}; // array needs to be sorted in ascending order
found = binarySearch(a, n, target);
if (found == -1) {
printf("Element not present in array\n");
} else {
printf("Element found at index %d\n", found);
}
return 0;
}