Skip to content

ts-ds / trace

Function: trace() ​

ts
function trace<T>(
   algorithm, 
   input, 
   compareFn?
): Trace<T>;

Defined in: trace/trace.ts:79

Records every comparison, read and write that a sorting algorithm makes, without changing the algorithm itself: the array is wrapped in a Proxy and the comparator in a counting function. The input array is not modified.

Without trace the algorithms run with no overhead at all — tracing costs only when you use it.

Type Parameters ​

Type ParameterDescription
T

Parameters ​

ParameterTypeDescription
algorithmSortFunction<T>Sorting function, e.g. quickSort or sort.merge.
inputreadonly T[]Array to sort. It is copied, not modified.
compareFn?CompareFn<T>Comparator passed to the algorithm; its default order is used when omitted.

Returns ​

Trace<T>

The input, the sorted output, the steps and the counters.

Example ​

ts
const { steps, stats } = trace(bubbleSort, [3, 1, 2]);
stats.comparisons; // 3
steps[1]; // { type: 'swap', i: 0, j: 1 }

MIT License