function mergesort
mergesort(
x: array | [array, array],
mode?: string,
): [array, array]

Sort array in ascending or descending order.

Mergesort is a divide-and-conquer algorithm that recursively splits an array into halves, sorts each half, and then merges them back together in the desired order. It returns the sorted values along with their original indexes.

Examples

Sort an array in ascending order with indexes

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(mergesort([9, -3, 2, -12, 0, 1]), [
  [-12, -3, 0, 1, 2, 9],
  [3, 1, 4, 5, 2, 0],
]);

Sort an array in descending order with indexes

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(mergesort([9, -3, 2, -12, 0, 1], 'descend'), [
  [9, 2, 1, 0, -3, -12],
  [0, 2, 5, 4, 1, 3],
]);

Sort an array of length 1

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(mergesort([5]), [[5], [0]]);

Invalid mode

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertThrows(() => mergesort([1, 2, 3], 'invalid'), "sorting must be \"ascend\" or \"descend\"");

Empty array

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(mergesort([]), [[], []]);

Array with repeated values

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(mergesort([3, 1, 3, 2, 3]), [
  [1, 2, 3, 3, 3],
  [1, 3, 0, 2, 4],
]);

Parameters

Array of elements to sort.

optional
mode: string = ascend

Sorting direction: "ascend" (default) or "descend".

Return Type

A 2D array: the first row contains sorted values, the second row contains the original indexes.

Throws

If no arguments are provided or the mode is invalid.