Algorithms

Pick the smallest remaining element and swap it into place — O(n²), at most n−1 swaps.

Version 1.1.0 Versions: 1.2.0 1.1.0 1.0.0

This is an older version. The current version is 1.2.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
# Selection Sort

Zerethon Official Sample `selection-sort`, version 1.1.0, Node.js 22.

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

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

function selectionSort(a) {
    const n = a.length;
    for (let i = 0; i < n - 1; i++) {
        let min = i;
        for (let j = i + 1; j < n; j++) {
            if (a[j] < a[min]) min = j;
        }
        if (min !== i) [a[i], a[min]] = [a[min], a[i]];
    }
    return a;
}

module.exports = { selectionSort };
test_selection_sort.js
// Checks for selectionSort. 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 { selectionSort } = require('./selection_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 = selectionSort([...c]);
    assert.deepStrictEqual(got, [...c].sort((x, y) => x - y), `selectionSort([${c.slice(0, 6)}...])`);
}

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

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