Path: blob/develop/src/sage/data_structures/binary_search.pyx
4054 views
# We can probably get away with only having the mpz_binary_searches in here.1# I'm too scared to get rid of it at 2am though.2cdef Py_ssize_t binary_search(Py_ssize_t* v, Py_ssize_t n, Py_ssize_t x, Py_ssize_t* ins) noexcept:3"""4Find the position of the integer x in the array v, which has length n.56Return -1 if x is not in the array v, and in this case ins is7set equal to the position where x should be inserted in order to8obtain an ordered array.9"""10if n == 0:11ins[0] = 012return -11314cdef Py_ssize_t i, j, k15i = 016j = n-117while i<=j:18if i == j:19if v[i] == x:20ins[0] = i21return i22if v[i] < x:23ins[0] = i + 124else:25ins[0] = i26return -127k = (i+j)/228if v[k] > x:29j = k-130elif v[k] < x:31i = k+132else: # only possibility is that v[k] == x33ins[0] = k34return k35# end while36ins[0] = j+137return -1383940cdef Py_ssize_t binary_search0(Py_ssize_t* v, Py_ssize_t n, Py_ssize_t x) noexcept:41"""42Find the position of the int x in the array v, which has length n.4344Return -1 if x is not in the array v.45"""46if n == 0:47return -14849cdef Py_ssize_t i, j, k50i = 051j = n-152while i<=j:53if i == j:54if v[i] == x:55return i56return -157k = (i+j)/258if v[k] > x:59j = k-160elif v[k] < x:61i = k+162else: # only possibility is that v[k] == x63return k64return -1656667