1 """Bisection algorithms."""
3 def insort_right(a
, x
, lo
=0, hi
=None):
4 """Insert item x in list a, and keep it sorted assuming a is sorted.
6 If x is already in a, insert it to the right of the rightmost x.
8 Optional args lo (default 0) and hi (default len(a)) bound the
9 slice of a to be searched.
13 raise ValueError('lo must be non-negative')
18 if x
< a
[mid
]: hi
= mid
22 insort
= insort_right
# backward compatibility
24 def bisect_right(a
, x
, lo
=0, hi
=None):
25 """Return the index where to insert item x in list a, assuming a is sorted.
27 The return value i is such that all e in a[:i] have e <= x, and all e in
28 a[i:] have e > x. So if x already appears in the list, a.insert(x) will
29 insert just after the rightmost x already there.
31 Optional args lo (default 0) and hi (default len(a)) bound the
32 slice of a to be searched.
36 raise ValueError('lo must be non-negative')
41 if x
< a
[mid
]: hi
= mid
45 bisect
= bisect_right
# backward compatibility
47 def insort_left(a
, x
, lo
=0, hi
=None):
48 """Insert item x in list a, and keep it sorted assuming a is sorted.
50 If x is already in a, insert it to the left of the leftmost x.
52 Optional args lo (default 0) and hi (default len(a)) bound the
53 slice of a to be searched.
57 raise ValueError('lo must be non-negative')
62 if a
[mid
] < x
: lo
= mid
+1
67 def bisect_left(a
, x
, lo
=0, hi
=None):
68 """Return the index where to insert item x in list a, assuming a is sorted.
70 The return value i is such that all e in a[:i] have e < x, and all e in
71 a[i:] have e >= x. So if x already appears in the list, a.insert(x) will
72 insert just before the leftmost x already there.
74 Optional args lo (default 0) and hi (default len(a)) bound the
75 slice of a to be searched.
79 raise ValueError('lo must be non-negative')
84 if a
[mid
] < x
: lo
= mid
+1
88 # Overwrite above definitions with a fast C implementation