Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sage
Path: blob/develop/src/sage/data_structures/binary_search.pyx
4054 views
1
# We can probably get away with only having the mpz_binary_searches in here.
2
# I'm too scared to get rid of it at 2am though.
3
cdef Py_ssize_t binary_search(Py_ssize_t* v, Py_ssize_t n, Py_ssize_t x, Py_ssize_t* ins) noexcept:
4
"""
5
Find the position of the integer x in the array v, which has length n.
6
7
Return -1 if x is not in the array v, and in this case ins is
8
set equal to the position where x should be inserted in order to
9
obtain an ordered array.
10
"""
11
if n == 0:
12
ins[0] = 0
13
return -1
14
15
cdef Py_ssize_t i, j, k
16
i = 0
17
j = n-1
18
while i<=j:
19
if i == j:
20
if v[i] == x:
21
ins[0] = i
22
return i
23
if v[i] < x:
24
ins[0] = i + 1
25
else:
26
ins[0] = i
27
return -1
28
k = (i+j)/2
29
if v[k] > x:
30
j = k-1
31
elif v[k] < x:
32
i = k+1
33
else: # only possibility is that v[k] == x
34
ins[0] = k
35
return k
36
# end while
37
ins[0] = j+1
38
return -1
39
40
41
cdef Py_ssize_t binary_search0(Py_ssize_t* v, Py_ssize_t n, Py_ssize_t x) noexcept:
42
"""
43
Find the position of the int x in the array v, which has length n.
44
45
Return -1 if x is not in the array v.
46
"""
47
if n == 0:
48
return -1
49
50
cdef Py_ssize_t i, j, k
51
i = 0
52
j = n-1
53
while i<=j:
54
if i == j:
55
if v[i] == x:
56
return i
57
return -1
58
k = (i+j)/2
59
if v[k] > x:
60
j = k-1
61
elif v[k] < x:
62
i = k+1
63
else: # only possibility is that v[k] == x
64
return k
65
return -1
66
67