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, Node.js 22.

- `merge_sort.js` — the algorithm, as shown in Zerethon Tools
- `main.js` — entry file: a short demonstration
- `test_merge_sort.js` — 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.js entry
const { mergeSort } = require('./merge_sort');

const numbers = [38, 27, 43, 3, 9, 82, 10, 27];
console.log(`Before: [${numbers.join(', ')}]`);
const result = mergeSort([...numbers]);
console.log(`After:  [${result.join(', ')}]`);
const expected = [...numbers].sort((x, y) => x - y);
console.log(`Same as sort(): ${result.join() === expected.join()}`);
merge_sort.js
// Merge Sort (Zerethon Official Sample: merge-sort 1.2.0).

function mergeSort(a) {
    if (a.length <= 1) return a;
    const mid = a.length >> 1;
    const left = mergeSort(a.slice(0, mid));
    const right = mergeSort(a.slice(mid));
    const out = [];
    let i = 0, j = 0;
    while (i < left.length && j < right.length) {
        out.push(left[i] <= right[j] ? left[i++] : right[j++]);
    }
    while (i < left.length) out.push(left[i++]);
    while (j < right.length) out.push(right[j++]);
    return out;
}

module.exports = { mergeSort };
test_merge_sort.js
// Checks for mergeSort. To run them, set this file as the entry file
// (the ▶ button next to it in Files) and press Run.
const assert = require('assert');
const { mergeSort } = require('./merge_sort');

/** Deterministic pseudo-random integers in [-50, 49]. */
function numbers(seed, count) {
    const out = [];
    for (let i = 0; i < count; i++) {
        seed = (seed * 1103515245 + 12345) % 2 ** 31;
        out.push((seed % 100) - 50);
    }
    return out;
}

const cases = [[], [1], [2, 1], [1, 2, 3], [3, 2, 1], [5, 1, 5, 1, 5], [-3, 0, -1, 2]];
for (const [seed, size] of [[1, 10], [2, 50], [3, 200]]) cases.push(numbers(seed, size));

for (const c of cases) {
    const got = mergeSort([...c]);
    assert.deepStrictEqual(got, [...c].sort((x, y) => x - y), `mergeSort([${c.slice(0, 6)}...])`);
}

console.log(`All ${cases.length} checks passed.`);

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