# SRT — Sort

Source: https://rungs.dev/docs/structured-text/instructions/srt

> SRT is the Structured Text instruction in rungs.dev that sorts a run of array elements into ascending order in place, using the length and position on its CONTROL tag.

Sorts a run of array elements into ascending order, in place. Modeled on the SRT instruction in
Logix 5000® controllers.

```iecst
SRT(Readings, 0, SortCtl);
```

After this statement, the first `SortCtl.LEN` elements of `Readings` are in ascending order.

## Operands [#operands]

| Name        | Type                          | Notes                                |
| ----------- | ----------------------------- | ------------------------------------ |
| `array`     | `DINT`, `INT`, `SINT`, `REAL` | `Readings` or `Readings[0]`          |
| `dimension` | the literal `0`               | Which dimension to vary              |
| `control`   | `CONTROL`                     | Holds the length and the status bits |

> **INFO**
>
> **Three arguments, not five**
>
> The Ladder box has Length and Position rows; the Structured Text form does not. Both come from
> the control tag's `.LEN` and `.POS` members instead. Set `.LEN` before the sort runs — on the
> tag's default, or with an assignment:
>
> ```iecst
> SortCtl.LEN := 5;
> SRT(Readings, 0, SortCtl);
> ```

`dimension` is always `0` — Studio supports
[single-dimension arrays only](https://rungs.dev/docs/tags/arrays#restrictions).

## After it runs [#after-it-runs]

`.POS` holds the index of the last element sorted, `.LEN - 1`. `.EN` and `.DN` turn on.

A run past the end of the array, or a negative `.LEN` or `.POS`, is a major fault: the scan
stops and nothing is sorted. Use [`SIZE`](https://rungs.dev/docs/structured-text/instructions/size) to keep `.LEN` honest:

```iecst
SIZE(Readings, 0, SortCtl.LEN);
SRT(Readings, 0, SortCtl);
```

## Related [#related]

- [SIZE](https://rungs.dev/docs/structured-text/instructions/size) — how many elements an array has
- [COP and CPS](https://rungs.dev/docs/structured-text/instructions/cop-cps) — keep a copy of the original order
- [SRT in Ladder](https://rungs.dev/docs/ladder-logic/instructions/srt)