Run of a sequence explained

In computer science, a run of a sequence is a non-decreasing range of the sequence that cannot be extended. The number of runs of a sequence is the number of increasing subsequences of the sequence. This is a measure of presortedness, and in particular measures how many subsequences must be merged to sort a sequence.

Definition

Let

X=\langlex1,...,xn\rangle

be a sequence of elements from a totally ordered set. A run of

X

is a maximal increasing sequence

\langlexi,xi+1,...,xj-1,xj\rangle

. That is,

xi-1>xi

and

xj>xj+1

assuming that

xi-1

and

xj+1

exists. For example, if

n

is a natural number, the sequence

\langlen+1,n+2,...,2n,1,2,...,n\rangle

has the two runs

\langlen+1,...,2n\rangle

and

\langle1,...,n\rangle

.

Let

runs(X)

be defined as the number of positions

i

such that

1\lei<n

and

xi+1<xi

. It is equivalently defined as the number of runs of

X

minus one. This definition ensure that

runs(\langle1,2,...,n\rangle)=0

, that is, the

runs(X)=0

if, and only if, the sequence

X

is sorted. As another example,

runs(\langlen,n-1,...,1\rangle)=n-1

and

runs(\langle2,1,4,3,...,2n,2n-1\rangle)=n

.

Sorting sequences with a low number of runs

The function

runs

is a measure of presortedness. The natural merge sort is

runs

-optimal. That is, if it is known that a sequence has a low number of runs, it can be efficiently sorted using the natural merge sort.

Long runs

A long run is defined similarly to a run, except that the sequence can be either non-decreasing or non-increasing. The number of long runs is not a measure of presortedness. A sequence with a small number of long runs can be sorted efficiently by first reversing the decreasing runs and then using a natural merge sort.

References