Algorithms

Split in half, sort each half, merge the sorted halves — O(n log n), stable.

Version 1.2.0 · current Versions: 1.2.0 1.1.0 1.0.0

Implementations

Sign in to open in IDE Sign in with your Zerethon account to create your own copy of this sample.

Files

README.md
# Merge Sort

Zerethon Official Sample `merge-sort`, version 1.2.0, PHP 8.4.

- `merge_sort.php` — the algorithm, as shown in Zerethon Tools
- `main.php` — entry file: a short demonstration
- `test_merge_sort.php` — checks; set it as the entry file to run them

This project is your own copy. Changing it never changes the official sample.
See the algorithm animated: https://tools.zerethon.com/merge-sort-visualizer
main.php entry
<?php

require __DIR__ . '/merge_sort.php';

$a = [38, 27, 43, 3, 9, 82, 10, 27];
echo 'Before: [' . implode(', ', $a) . "]\n";
$result = merge_sort($a);
echo 'After:  [' . implode(', ', $result) . "]\n";
$expected = $a;
sort($expected);
echo 'Same as sort(): ' . ($result === $expected ? 'true' : 'false') . "\n";
merge_sort.php
<?php

// Merge Sort (Zerethon Official Sample: merge-sort 1.2.0).
// The algorithm as shown in Zerethon Tools.

function merge_sort(array $a): array {
    if (count($a) <= 1) return $a;
    $mid = intdiv(count($a), 2);
    $left = merge_sort(array_slice($a, 0, $mid));
    $right = merge_sort(array_slice($a, $mid));
    $out = [];
    $i = $j = 0;
    while ($i < count($left) && $j < count($right)) {
        $out[] = ($left[$i] <= $right[$j]) ? $left[$i++] : $right[$j++];
    }
    while ($i < count($left))  $out[] = $left[$i++];
    while ($j < count($right)) $out[] = $right[$j++];
    return $out;
}
test_merge_sort.php
<?php

// Checks for merge_sort. To run them, set this file as the entry file
// (the ▶ button next to it in Files) and press Run.

require __DIR__ . '/merge_sort.php';

/** Deterministic pseudo-random integers in [-50, 49] (the same as the Python checks). */
function numbers(int $seed, int $count): array
{
    $out = [];
    for ($i = 0; $i < $count; $i++) {
        $seed = ($seed * 1103515245 + 12345) % 2 ** 31;
        $out[] = $seed % 100 - 50;
    }

    return $out;
}

$cases = [[], [1], [2, 1], [1, 2, 3], [3, 2, 1], [5, 1, 5, 1, 5], [-3, 0, -1, 2]];
foreach ([[1, 10], [2, 50], [3, 200]] as [$seed, $size]) {
    $cases[] = numbers($seed, $size);
}

foreach ($cases as $a) {
    $result = merge_sort($a);
    $expected = $a;
    sort($expected);
    if ($result !== $expected) {
        fwrite(STDERR, 'merge_sort([' . implode(', ', array_slice($a, 0, 6)) . "...]) is wrong\n");
        exit(1);
    }
}

echo 'All ' . count($cases) . " checks passed.\n";

Source: Zerethon Official Sample. Algorithm as shown in the Zerethon Tools Merge Sort Visualizer.