-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy path8.c
More file actions
38 lines (32 loc) · 658 Bytes
/
Copy path8.c
File metadata and controls
38 lines (32 loc) · 658 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
#include <stdio.h>
int binary_search(int *numbers, int n, int x)
{
int left = 0;
int right = n - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (numbers[mid] == x)
{
return mid;
}
else if (numbers[mid] < x)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}
int main()
{
int numbers[] = { 1, 3, 5, 7, 12};
int count = sizeof(numbers) / sizeof(numbers[0]);
int x = 7;
int index = binary_search(numbers, count, x);
printf("Index of %d is %d\n", x, index);
return 0;
}