Bisect   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 12
eloc 31
c 1
b 0
f 0
dl 0
loc 71
ccs 31
cts 31
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A left() 0 26 5
A right() 0 26 5
A checkArrayKeys() 0 4 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ddlzz\Bisect;
6
7
use Ddlzz\Bisect\Exception\InvalidArrayKeysException;
8
9
class Bisect
10
{
11
    /**
12
     * @throws InvalidArrayKeysException
13
     */
14 10
    public static function left(array $sortedArray, $value, int $leftKey = 0, int $rightKey = null): int
15
    {
16 10
        self::checkArrayKeys($sortedArray);
17
18 9
        $arraySize = \count($sortedArray);
19 9
        $rightKey = $rightKey ?? $arraySize - 1;
20
21 9
        if ($value < $sortedArray[$leftKey]) {
22 1
            return 0;
23
        }
24
25 8
        if ($value >= $sortedArray[$rightKey]) {
26 2
            return $arraySize;
27
        }
28
29 6
        while ($leftKey < $rightKey) {
30 6
            $middle = (int) (($leftKey + $rightKey) / 2);
31
32 6
            if ($sortedArray[$middle] < $value) {
33 5
                $leftKey = $middle + 1;
34
            } else {
35 6
                $rightKey = $middle;
36
            }
37
        }
38
39 6
        return $rightKey;
40
    }
41
42
    /**
43
     * @throws InvalidArrayKeysException
44
     */
45 9
    public static function right(array $sortedArray, $value, int $leftKey = 0, int $rightKey = null): int
46
    {
47 9
        self::checkArrayKeys($sortedArray);
48
49 9
        $arraySize = \count($sortedArray);
50 9
        $rightKey = $rightKey ?? $arraySize - 1;
51
52 9
        if ($value < $sortedArray[$leftKey]) {
53 1
            return 0;
54
        }
55
56 8
        if ($value >= $sortedArray[$rightKey]) {
57 2
            return $arraySize;
58
        }
59
60 6
        while ($leftKey < $rightKey) {
61 6
            $middle = (int) (($leftKey + $rightKey) / 2);
62
63 6
            if ($value < $sortedArray[$middle]) {
64 6
                $rightKey = $middle;
65
            } else {
66 6
                $leftKey = $middle + 1;
67
            }
68
        }
69
70 6
        return $rightKey;
71
    }
72
73
    /**
74
     * @throws InvalidArrayKeysException
75
     */
76 19
    private static function checkArrayKeys(array $sortedArray): void
77
    {
78 19
        if ($sortedArray !== array_values($sortedArray)) {
79 1
            throw new InvalidArrayKeysException('Array keys must be sorted numerically.');
80
        }
81
    }
82
}
83