BinarySelection.index_of()   B
last analyzed

Complexity

Conditions 7

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 7
c 2
b 1
f 0
dl 0
loc 20
rs 7.3333
1
from pyalgs.algorithms.commons.util import is_sorted, less
2
3
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