LoginSignup
6
1

More than 3 years have passed since last update.

計算量O(n)の革命的なソートアルゴリズムをPHPでも

Posted at

計算量O(n)の画期的なソートアルゴリズムであるスターリンソートをHaskell で実装してみた #Haskell - Qiita

スターリンソートは当然、PHPでも簡単に実装することができます。 https://3v4l.org/g9bR2

<?php

namespace stalin;

function sort(array $xs): array
{
    if (count($xs) <= 1) {
        return $xs;
    }

    $zs = $xs;
    $x = array_shift($zs);
    $y = array_shift($zs);

    if ($x <= $y) {
        return [$x, ...sort([$y, ...$zs])];
    }

    return sort([$x, ...$zs]);
}

動かしてみます。

echo json_encode(\stalin\sort([1, 2, 1, 1, 4, 3, 9]));
// [1,2,4,9]

完璧ですね。 PHP 7.3? そんな古いバージョンのことは知りません

参考

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1