-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_search.c
77 lines (66 loc) · 1.33 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
65
66
67
68
69
70
71
72
73
74
75
76
77
// Licensed under the MIT License.
#include <stdlib.h>
#include "binary_search.h"
Object binary_search_min(
Object min,
Array items,
size_t length,
size_t itemSize,
Comparer comparer)
{
if (!length)
{
return NULL;
}
char* buffer = items;
size_t left = 0;
size_t right = length - 1;
while (left < right)
{
size_t index = left + (right - left) / 2;
int comparison = comparer(buffer + index * itemSize, min);
if (comparison < 0)
{
left = index + 1;
}
else if (comparison > 0)
{
right = index;
}
else
{
return buffer + index * itemSize;
}
}
return buffer + right * itemSize;
}
size_t binary_search_rank(
Object max,
Array items,
size_t length,
size_t itemSize,
Comparer comparer)
{
if (!length)
{
return 0;
}
char* buffer = items;
size_t left = 0;
size_t right = length - 1;
size_t result = 0;
while (left <= right)
{
size_t index = left + (right - left) / 2;
if (comparer(buffer + index * itemSize, max) < 0)
{
result = index + 1;
left = index + 1;
}
else
{
right = index - 1;
}
}
return result;
}