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