blob: 47ef509a9b31fb59f13a8168f06955200c166330 [file] [log] [blame]
Guido van Rossum4acc25b2000-02-02 15:10:15 +00001"""Bisection algorithms."""
Guido van Rossum4e160981992-09-02 20:43:20 +00002
3
Guido van Rossumd5484fb1997-10-07 14:45:49 +00004def insort(a, x, lo=0, hi=None):
Guido van Rossum4acc25b2000-02-02 15:10:15 +00005 """Insert item x in list a, and keep it sorted assuming a is sorted."""
6 if hi is None:
7 hi = len(a)
8 while lo < hi:
9 mid = (lo+hi)/2
10 if x < a[mid]: hi = mid
11 else: lo = mid+1
12 a.insert(lo, x)
Guido van Rossum4e160981992-09-02 20:43:20 +000013
14
Guido van Rossumd5484fb1997-10-07 14:45:49 +000015def bisect(a, x, lo=0, hi=None):
Guido van Rossum4acc25b2000-02-02 15:10:15 +000016 """Find the index where to insert item x in list a, assuming a is sorted."""
17 if hi is None:
18 hi = len(a)
19 while lo < hi:
20 mid = (lo+hi)/2
21 if x < a[mid]: hi = mid
22 else: lo = mid+1
23 return lo