-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.c
More file actions
65 lines (51 loc) · 1.23 KB
/
binary_search.c
File metadata and controls
65 lines (51 loc) · 1.23 KB
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
/** binary_search.c
* @brief Uses binary search to find a target.
* @author Eric Taylor
* @date 09/21/2025
*/
#include <stdio.h>
#include <stdlib.h>
// Returns a pointer to the found element:
int* search(int* nums, int length, int target) {
int* first = nums;
int* last = &nums[length - 1];
int* mid;
int jump;
for (jump = length; first <= last; jump /= 2) {
mid = (first + (jump / 2));
if (*mid < target) {
first = (mid + 1);
continue;
}
if (*mid > target) {
last = (mid - 1);
continue;
}
if (*mid == target) {
return mid;
}
}
return NULL;
}
int* get_nums(int length) {
int* nums = (int*) malloc((length) * sizeof(int));
for (int i = 0; i < length; i++) {
nums[i] = i;
}
return nums;
}
int main() {
int target = 30000000;
int LENGTH = 100000000;
int* nums = get_nums(LENGTH);
int* found = search(nums, LENGTH, target);
free(nums);
nums = NULL;
if (found == NULL) {
printf("Target: %d not found\n", target);
return 0;
}
printf("Target: %d\n", target);
printf("Found: %d at %p\n", *found, found);
return 0;
}