phpOMS/Algorithm/Sort/BitonicSort.php

64 lines
1.5 KiB
PHP

<?php
/**
* Orange Management
*
* PHP Version 7.4
*
* @package phpOMS\Algorithm\Sort;
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link https://orange-management.org
*/
declare(strict_types=1);
namespace phpOMS\Algorithm\Sort;
/**
* BitonicSort class.
*
* @package phpOMS\Algorithm\Sort;
* @license OMS License 1.0
* @link https://orange-management.org
* @since 1.0.0
*/
class BitonicSort implements SortInterface
{
public static function sort(array $list, int $order = SortOrder::ASC) : array
{
$n = \count($list);
if ($n < 2) {
return $list;
}
$first = self::sort(\array_slice($list, 0, $n / 2), SortOrder::ASC);
$second = self::sort(\array_slice($list, $n / 2), SortOrder::DESC);
return self::merge(\array_merge($first, $second), $order);
}
public static function merge(array $list, int $order) : array
{
$n = \count($list);
if ($n === 1) {
return $list;
}
$dist = $n / 2;
for ($i = 0; $i < $dist; ++$i) {
if ($list[$i]->compare($list[$i + $dist], $order)) {
$old = $list[$i];
$list[$i] = $list[$i + $dist];
$list[$i + $dist] = $old;
}
}
$first = self::merge(\array_slice($list, 0, $n / 2), $order);
$second = self::merge(\array_slice($list, $n / 2), $order);
return \array_merge($first, $second);
}
}