-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbinary_search.c
64 lines (50 loc) · 1.08 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
#include <stdio.h>
#include <stdlib.h>
/**
* Binary search algorithm.
*
* @param int a Search array
* @param int find Data to search
* @param int n Number of data in search array
*
* @return int Index of found data or -1
*/
int binary_search(int *a, int find, int n)
{
int start = 0;
int end = n - 1;
int mid = n / 2;
while (start <= end) {
if (a[mid] == find) {
return mid;
}
if (find < a[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
mid = (start + end) / 2;
}
return -1;
}
int main()
{
int n, find;
printf("How many items? ");
scanf("%d", &n);
int *input = (int *) malloc(n * sizeof(int));
printf("Enter numbers: ");
for (int i = 0; i < n; i++) {
scanf("%d", input + i);
}
printf("Find: ");
scanf("%d", &find);
int position = binary_search(input, find, n);
if (position != -1) {
printf("Data found at position %d", position);
} else {
printf("Data not found");
}
free(input);
return 0;
}