| Total Complexity | 7 |
| Total Lines | 21 |
| Duplicated Lines | 0 % |
| Changes | 2 | ||
| Bugs | 1 | Features | 0 |
| 1 | from pyalgs.algorithms.commons.util import is_sorted, less |
||
| 4 | class BinarySelection(object): |
||
| 5 | @staticmethod |
||
| 6 | def index_of(a, x, lo=None, hi=None): |
||
| 7 | if not is_sorted(a): |
||
| 8 | raise ValueError('array must be sorted before running selection') |
||
| 9 | |||
| 10 | if lo is None: |
||
| 11 | lo = 0 |
||
| 12 | if hi is None: |
||
| 13 | hi = len(a) - 1 |
||
| 14 | |||
| 15 | while lo <= hi: |
||
| 16 | mid = lo + (hi - lo) // 2 |
||
| 17 | if less(x, a[mid]): |
||
| 18 | hi = mid - 1 |
||
| 19 | elif less(a[mid], x): |
||
| 20 | lo = mid + 1 |
||
| 21 | else: |
||
| 22 | return mid |
||
| 23 | |||
| 24 | return -1 |
||
| 25 |