# SORT

## Purpose:

Rearranges the values of a series in descending or ascending numerical order.

## Syntax:

SORT(series, order)

(v, idx) = SORT(series, order)

series

-

A series or table.

order

-

Optional. An integer or string, the sort direction.

 0 or "descend" : descending order (default) 1 or "ascend" : ascending order

## Returns:

A sorted series or table.

(v, idx) = SORT(series, order) returns the sorted series and the indices of the sorted values in separate series.

## Example:

W1: {2, 1, 4, 5, 3, 6}

W2: sort(W1)

W3: sort(W1, 0)

W4: sort(W1, "descend")

W2, W3 and W4 contain the series {6, 5, 4, 3, 2, 1}

## Example:

W1: {2, 1, 4, 5, 3, 6}

W2: sort(W1, 1)

W3: sort(W1, "ascend")

W2 and W3 contain the series {1, 2, 3, 4, 5, 6}

## Example:

W1: {2, 1, 4, 5, 3, 6}

(v, idx) = sort(W1, 1)

v   == {1, 2, 3, 4, 5, 6}

idx == {2, 1, 5, 3, 4, 6}

W1[idx] == {1, 2, 3, 4, 5, 6}

## Example:

W1: {2, 1, 1, 3, 2}

(v, idx) = sort(W1, 1)

v   == {1, 1, 2, 2, 3}

idx == {2, 3, 1, 5, 4}

W1[idx] == {1, 1, 2, 2, 3}

The original order of duplicate values is preserved.

## Example:

W1: {2, nan, nan, inf, 2}

(v1, idx1) = sort(W1, 1);

(v2, idx2) = sort(W1, 0);

v1   == {2, 2, inf, nan, nan}

idx1 == {1, 5, 4, 2, 3}

v2   == {nan, nan, inf, 2, 2}

idx2 == {2, 3, 4, 1, 5}

NaN values are placed at the end of an ascending sort and the beginning of a descending sort.

## Example:

W1: {0.8 + i, -1 + i, -0.9 + i}

W2: sort(w1)

W3: sort(real(w1))

W2 == {-1 + i, -0.9 + i, 0.8 + i}

W3 == {0.8, -0.9, -1.0}

Complex values are sorted by magnitude first and if equal, by phase.

## Remarks:

SORT performs a stable sort such that the original order of duplicate values is preserved.

SORT employs the "Timsort" method, a combination of modified insertion and merge sorts optimized for real world data where the series contains stretches of already sorted values. The fastest speed will occur when the length of the series is less than or equal to the buffer size as specified by SETBUFSIZE.

Complex values are sorted by magnitude first. If the magnitudes of the compared values are equal, the values are sorted on phase from -π to π. If the imaginary parts of the compared complex values are 0, the real part (including sign) instead of the magnitude is the first sort criterion.

SORT returns a table with each column sorted in ascending/descending order. To sort a table based on a column, see REORDER.

CPLXPAIR