blob: 343bd5da81b64200293e763b189adf2d56396d13 [file] [log] [blame]
Guido van Rossum4acc25b2000-02-02 15:10:15 +00001"""Bisection algorithms."""
Guido van Rossum4e160981992-09-02 20:43:20 +00002
3
Tim Peters36cdad12000-12-29 02:06:45 +00004def insort_right(a, x, lo=0, hi=None):
5 """Insert item x in list a, and keep it sorted assuming a is sorted.
6
7 If x is already in a, insert it to the right of the rightmost x.
8
9 Optional args lo (default 0) and hi (default len(a)) bound the
10 slice of a to be searched.
11 """
12
Guido van Rossum4acc25b2000-02-02 15:10:15 +000013 if hi is None:
14 hi = len(a)
15 while lo < hi:
16 mid = (lo+hi)/2
17 if x < a[mid]: hi = mid
18 else: lo = mid+1
19 a.insert(lo, x)
Guido van Rossum4e160981992-09-02 20:43:20 +000020
Tim Peters36cdad12000-12-29 02:06:45 +000021insort = insort_right # backward compatibility
Guido van Rossum4e160981992-09-02 20:43:20 +000022
Tim Peters36cdad12000-12-29 02:06:45 +000023def bisect_right(a, x, lo=0, hi=None):
24 """Return the index where to insert item x in list a, assuming a is sorted.
25
26 The return value i is such that all e in a[:i] have e <= x, and all e in
27 a[i:] have e > x. So if x already appears in the list, i points just
28 beyond the rightmost x already there.
29
30 Optional args lo (default 0) and hi (default len(a)) bound the
31 slice of a to be searched.
32 """
33
Guido van Rossum4acc25b2000-02-02 15:10:15 +000034 if hi is None:
35 hi = len(a)
36 while lo < hi:
37 mid = (lo+hi)/2
38 if x < a[mid]: hi = mid
39 else: lo = mid+1
40 return lo
Tim Peters36cdad12000-12-29 02:06:45 +000041
42bisect = bisect_right # backward compatibility
43
44def insort_left(a, x, lo=0, hi=None):
45 """Insert item x in list a, and keep it sorted assuming a is sorted.
46
47 If x is already in a, insert it to the left of the leftmost x.
48
49 Optional args lo (default 0) and hi (default len(a)) bound the
50 slice of a to be searched.
51 """
52
53 if hi is None:
54 hi = len(a)
55 while lo < hi:
56 mid = (lo+hi)/2
57 if a[mid] < x: lo = mid+1
58 else: hi = mid
59 a.insert(lo, x)
60
61
62def bisect_left(a, x, lo=0, hi=None):
63 """Return the index where to insert item x in list a, assuming a is sorted.
64
65 The return value i is such that all e in a[:i] have e < x, and all e in
66 a[i:] have e >= x. So if x already appears in the list, i points just
67 before the leftmost x already there.
68
69 Optional args lo (default 0) and hi (default len(a)) bound the
70 slice of a to be searched.
71 """
72
73 if hi is None:
74 hi = len(a)
75 while lo < hi:
76 mid = (lo+hi)/2
77 if a[mid] < x: lo = mid+1
78 else: hi = mid
79 return lo