SRT — Sort

SRT in rungs.dev sorts a run of array elements into ascending order, in place. Use it to find a median, rank readings, or order a batch before working through it.

SRT

Array

array

(DN)

Dimension

dimension

(ER)

Control

control

Length

length

Position

position

Sorts a run of array elements into ascending order, in place.

What it is for

Sorting is how you find a median — sort the readings and take the middle one. A median throws away a single wild sample in a way an average cannot, which makes it the better choice for a sensor that occasionally spikes.

It is also how you rank things: sort the batch, then work through it smallest first.

"In place" means the array itself is reordered. There is no separate destination, and the original order is gone.

Operands

NameTypeNotes
arrayDINT, INT, SINT, REALWhere the run starts — Samples or Samples[2]
dimensionthe number 0Which dimension to vary
controlCONTROLThe instruction's state
lengthnumberHow many elements to sort
positionnumberNot used. Leave it 0

Elements outside [start, start + length) are never moved.

How It Works

SRT is a one-shot: it sorts on the scan the rung goes true and not again while it stays true, even if you scramble the array in between.

What arms it is .DN, not .EN — which matters if you ever write the bits yourself:

You write, with the rung still trueWhat happens
.EN := 0Nothing. .EN stays 0
.DN := 0Sorts again, at once

That is the opposite of the FIFO instructions, where the enable bit is the whole latch.

Afterwards .POS sits on the last element sorted, .LEN - 1. Unlike AVE, a false rung keeps .POS — it survives a restart too.

A run past the end of the array stops the program

Where AVE and STD stop quietly with .ER, SRT raises a major fault. Studio checks the number you type against the declared size; a .LEN written from logic is checked while the program runs. A negative .LEN or .POS is a major fault as well.

Example — Median of Five

Sort five readings and take the middle one.

0

Sample

SRT

Array

Readings

(DN)

Dimension

0

(ER)

Control

SortCtl

Length

5

Position

0

1

Sample

MOVE

Source

Readings[2]

Dest

Median

Both rungs run on the same scan, and rungs run top to bottom, so the MOVE reads the array after the sort.

Structured Text

SRT has a Structured Text form, and it is the short one — three arguments, not five:

SRT(Readings, 0, SortCtl);

The length and position come from SortCtl.LEN and SortCtl.POS, not from arguments. Set .LEN on the tag or with a MOVE before the sort runs.

Common Mistakes

  • Expecting the original order back. It is gone — copy the array first with COP if you need it.
  • Passing five arguments to the Structured Text form. It takes three.
  • Sorting more elements than the array holds. That stops the program.
  • Clearing .EN to make it sort again. Clear .DN.

On this page