-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinarySearch.c
More file actions
38 lines (32 loc) · 775 Bytes
/
binarySearch.c
File metadata and controls
38 lines (32 loc) · 775 Bytes
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
// binary search
#include <stdio.h>
void search(int*, int, int);
int main(){
int arr[] = {2, 5, 7, 13, 45, 67, 89};
int *hp = &arr[0];
int n = sizeof(arr) / sizeof(arr[0]);
int target = 5;
search(hp, n, target);
}
void search(int *head, int size, int target) {
int start = 0;
int end = size - 1;
int found = 0;
while(start <= end) {
int mid = (start + end) / 2;
if (*(head + mid) > target) {
end = mid - 1;
}
else if (*(head + mid) < target) {
start = mid + 1;
}
else {
printf("Element found at: %d \n", mid);
found = 1;
break;
}
}
if (found == 0) {
printf("Not found in array");
}
}