# Array list: insert at position

Algorithmic problem: Ordered sequence: insert at position

Type of algorithm: loop

Auxiliary data:

1. A natural number sum $\in \mathbb{N}_0$, which contains the total number of all elements seen so far in the visited arrays.
2. Two pointers, $p$ and $p'$, of type "pointer to array list item of type $\mathcal{K}$".

## Abstract view

Invariant:After $i \ge 0$ iterations:

1. The pointer $p$ points to the array at position $i+1$ in the array list.
2. It is sum$= n_1 + \ldots + n_i$, where $n_j$ is the value of the component n of the array list item at position $j \in \{1, \ldots,i\}$.

Variant: The pointer $p$ is moved one step forward to the next array.

Break condition: It is sum $+ p.n \ge\ell$.

## Induction basis

Abstract view: Set $p:=$first and sum$:=0$.

Implementation: Obvious.

Proof: Nothing to show.

## Induction step

Abstract view: If the position $\ell$ is in the current array, insert $K$ (if the array is full, split it first).

Implementation:

1. If $p=$ void, terminate the algorithm and return false.
2. If sum$+ p.n \lt \ell$:
1. Set sum$:=$sum$+ p.n$.
2. Set $p:=p$.next.
3. Otherwise:
1. If $p.n=N$:
1. Create a new array list item and let $p'$ point to this new list item.
2. Set $p'$.next$=p$.next.
3. Set $p$.next$:=p'$.
4. For $j \in \{1, \ldots, \lfloor p.n/2 \rfloor \}$, set $p'.A[\lceil j \rceil]:=p.A[\lceil p.n/2 \rceil + j ]$ and $p.A[\lceil p.n/2 \rceil + j]:=$void.
5. Set $p'.n:=\lfloor p.n/2 \rfloor$ and, afterwards, $p.n:=p.n - \lfloor p.n/2 \rfloor$.
2. If $l -$sum$\gt p.n$:
1. Set $m:=l -$ sum $- p.n + 1$.
2. Set $p:=p'$.
3. Otherwise, set $m:=l -$sum$+ 1$.
4. For $j=p.n, \ldots, m$ (in this order), set $p.A[j+1]:=p.A[j]$.
5. Set $p.A[m]:=K$.
4. Return true.

Correctness: Note that, in an implementation of Ordered sequence: insert at position, we may assume $l \leq$number(). Therefore, we do not have to care about the end of the list. In the case sum$+ p.n \lt l$, we simply have to update sum and $p$, which is obviously done correctly. So consider the case sum$+ p.n \ge l$, which means that the position where $K$ has to be inserted is in the array list item to which $p$ currently points. If that array is full, new space must be allocated. Step 2.1 does that and distributes the elements roughly equally over both items. Steps 2.2 - 2.3 ensure that $p$ points to the array where to insert $K$ and $m$ identifies the correct insert position. Step 2.4 empties the array component where to insert the new element by moving, exactly one position forward, the value at the position and the values at all later position (which is possible because the array is not full in any case).

## Complexity

Statement: Linear in the length of the sequence in the worst case.

Proof: Obvious.