Run of a sequence

From testwiki
Jump to navigation Jump to search

Template:More footnotes

Template:More citations needed 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=⟨x1,…,xn⟩ be a sequence of elements from a totally ordered set. A run of X is a maximal increasing sequence ⟨xi,xi+1,…,xj−1,xj⟩. That is, xi−1>xi and xj>xj+1Template:Clarify assuming that xi−1 and xj+1 exists. For example, if n is a natural number, the sequence ⟨n+1,n+2,…,2n,1,2,…,n⟩ has the two runs ⟨n+1,…,2n⟩ and ⟨1,…,n⟩.

Let 𝚛𝚞𝚗𝚜(X) be defined as the number of positions i such that 1≤i<n and xi+1<xi. It is equivalently defined as the number of runs of X minus one. This definition ensure that 𝚛𝚞𝚗𝚜(⟨1,2,…,n⟩)=0, that is, the 𝚛𝚞𝚗𝚜(X)=0 if, and only if, the sequence X is sorted. As another example, 𝚛𝚞𝚗𝚜(⟨n,n−1,…,1⟩)=n−1 and 𝚛𝚞𝚗𝚜(⟨2,1,4,3,…,2n,2n−1⟩)=n.

Sorting sequences with a low number of runs

The function 𝚛𝚞𝚗𝚜 is a measure of presortedness. The natural merge sort is 𝚛𝚞𝚗𝚜-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