Array Timsort

1.0.3 · maintenance · verified Sun Apr 19

The `array-timsort` package provides a JavaScript implementation of Python's highly optimized Timsort algorithm for stable array sorting. It is currently at version 1.0.3, with an apparent maintenance-only release cadence based on its last commit over two years ago. Unlike the `timsort` package it was forked from, `array-timsort` returns an array representing the original indices of elements after sorting, rather than `undefined`. Timsort is an adaptive, stable sorting algorithm that leverages existing order in data, achieving O(n) performance on partially sorted arrays and O(n log n) worst-case time complexity, with O(n) memory usage. Benchmarks suggest it can significantly outperform `Array.prototype.sort()` in Node.js for specific data distributions, such as descending arrays or those with many duplicates, while potentially being slower on certain random distributions.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic array sorting with a custom comparator, in-place modification, and sorting a specific subrange, highlighting the returned index map.

const { sort } = require('array-timsort');

// Example 1: Sorting a basic numerical array in ascending order
// The Timsort algorithm is adaptive and stable, making it efficient
// for partially sorted data while maintaining element order for equal values.
const numbers = [30, 10, 20, 5, 15, 25, 40, 35, 45, 0];
console.log('Original numbers:', numbers.slice()); // Log a copy to show original state

// Define a numerical comparison function
function numberCompare(a, b) {
    return a - b;
}

// Perform the sort using the custom comparator
// The `sort` function modifies the array in-place and returns
// an array of original indices mapping to their new positions.
const originalIndicesMap = sort(numbers, numberCompare);

console.log('Sorted numbers:', numbers);
console.log('Original indices map:', originalIndicesMap);

// Example 2: Sorting a specific subrange of an array
const mixedArray = ['apple', 'zebra', 'banana', 'grape', 'fig', 'date', 'elderberry'];
console.log('\nOriginal mixed array:', mixedArray.slice());

// Sort elements from index 2 ('banana') up to (but not including) index 6 ('elderberry') alphabetically
sort(mixedArray, 2, 6); 

console.log('Mixed array with subrange sorted:', mixedArray);

view raw JSON →