user
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Insertion sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |

An O(*n*2) sorting algorithm which moves elements one at a time into the correct position.
The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary.
To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part.

Although insertion sort is an O(*n*2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:

:   1. small   *n*,
    2. as the final finishing-off algorithm for O(*n* log*n*) algorithms such as mergesort and quicksort.

The algorithm is as follows (from wikipedia):

```
function insertionSort(array A)
    for i from 1 to length[A]-1 do
        value := A[i] 
        j := i-1
        while j >= 0 and A[j] > value do
            A[j+1] := A[j]
            j := j-1
        done
        A[j+1] = value
    done

```

Writing the algorithm for integers will suffice.
assistant
(formerly Perl 6)

```
sub insertion_sort ( @a is copy ) {
    for 1 .. @a.end -> $i {
        my $value = @a[$i];
        my $j;
        loop ( $j = $i-1; $j >= 0 and @a[$j] > $value; $j-- ) {
            @a[$j+1] = @a[$j];
        }
        @a[$j+1] = $value;
    }
    return @a;
}

my @data = 22, 7, 2, -5, 8, 4;
say 'input  = ' ~ @data;
say 'output = ' ~ @data.&insertion_sort;
```

Output:

```
input  = 22 7 2 -5 8 4
output = -5 2 4 7 8 22

```