impl. early return

This commit is contained in:
Dennis Eichhorn 2020-06-05 09:51:47 +02:00 committed by GitHub
parent 50ca46b5a9
commit ebd709d4cb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -45,36 +45,37 @@ final class MonotoneChain
*/ */
public static function createConvexHull(array $points) : array public static function createConvexHull(array $points) : array
{ {
if (($n = \count($points)) > 1) { if (($n = \count($points)) < 2) {
\uasort($points, [self::class, 'sort']); return $points;
}
\uasort($points, [self::class, 'sort']);
$k = 0; $k = 0;
$result = []; $result = [];
// Lower hull // Lower hull
for ($i = 0; $i < $n; ++$i) { for ($i = 0; $i < $n; ++$i) {
while ($k >= 2 && self::cross($result[$k - 2], $result[$k - 1], $points[$i]) <= 0) { while ($k >= 2 && self::cross($result[$k - 2], $result[$k - 1], $points[$i]) <= 0) {
--$k; --$k;
}
$result[$k++] = $points[$i];
} }
// Upper hull $result[$k++] = $points[$i];
for ($i = $n - 2, $t = $k + 1; $i >= 0; --$i) {
while ($k >= $t && self::cross($result[$k - 2], $result[$k - 1], $points[$i]) <= 0) {
--$k;
}
$result[$k++] = $points[$i];
}
\ksort($result);
return \array_slice($result, 0, $k - 1);
} }
return $points; // Upper hull
for ($i = $n - 2, $t = $k + 1; $i >= 0; --$i) {
while ($k >= $t && self::cross($result[$k - 2], $result[$k - 1], $points[$i]) <= 0) {
--$k;
}
$result[$k++] = $points[$i];
}
\ksort($result);
/** @return array<int, array{x:int|float, y:int|float}> */
return \array_slice($result, 0, $k - 1);
} }
/** /**