# Insertion sort (Standard ML)

### From LiteratePrograms

**Other implementations**: ACL2 | C | C, simple | Eiffel | Erlang | Forth | Haskell | Io | Java | Lisp | OCaml | Python | Python, arrays | Ruby | Scala, list | Smalltalk |**Standard ML**| Visual Basic .NET

**This program is under development.**

Please help to

**debug it**. When debugging

is complete, remove the {{develop}} tag.

This is a simple example of the insertion sort sorting algorithm, written in Standard ML. Standard ML offers both mutable and immutable data-structures, so we will show an imperative implementation to sort an array in-place and a functional implementation to sort a list.

We will sort the data of type `'a`

with a comparator function `cmp : 'a * 'a -> order`

.

## Contents |

## Sorting in place

### Implementation

When sorting an array with insertion sort, we conceptually separate it into two parts:

- The array of elements already inserted, which is always in sorted order and is found at the beginning of the array;
- The array of elements we have yet to insert, following.

In outline, our primary function looks like this:

<<insertion_sort_mutable.sml>>=funinsertion_sort cmp a = Array.appi(fn(i, v)=> insert v into sorted sublist)a

Here, the index `i`

represents both the index of the next element to insert and the length of the sorted sublist constructed so far.

To insert each element, we need to create a hole in the array at the place where the element belongs, then place the element in that hole. We can combine the creation of the hole with the searching for the place by starting at the end and shifting each element up by one until we find the place where the element belongs. This overwrites the element we're inserting, so we have to save it in a variable first:

<<insert v into sorted sublist>>=(* Insert v into the sorted sublist *)letvalj = ref(i - 1)inwhile!j >= 0andalsocmp(Array.sub(a, !j), v)= GREATERdo(Array.update(a, !j + 1, Array.sub(a, !j)); j := !j - 1); Array.update(a, !j + 1, v)end

You must be aware that the average and worse case time complexity of `insertion_sort a`

are *O*(*N*^{2}) where *N* = `Array.length a`

hence it is not recommended in practice (use a *O*(*N*log*N*) algorithm instead).

### Testing

There are several ways to compile sml code but for testing we recommend you to use the interactive toplevel `sml`

(in SML/NJ the `-`

is the prompt and start the lines you type in, the other lines are the answers of the system):

-vala = Array.fromList[5, 3, 1];vala =[|5,3,1|]: int array - insertion_sort Int.compare a;valit =(): unit - a;valit =[|1,3,5|]: int array

## Sorting immutable lists

### Implementation

As above, we will make a function `insertion_sort : ('a * 'a -> order) -> 'a list -> 'a list`

that will take a comparator function `cmp`

and a list and return the list sorted.

The empty list `[]`

is already sorted:

<<insertion_sort_immutable.sml>>=funinsertion_sort _[]=[]

If the list is not empty it consists of a first element `x`

followed by the remaining part of the list `xs`

. We sort `xs`

and insert `x`

at the right place:

<<insertion_sort_immutable.sml>>=| insertion_sort cmp(x::xs)= insert cmp x(insertion_sort cmp xs)

It remains to write `insert`

. Again, this is done by recursing on the list. Inserting an element `x`

into the empty list is easy:

<<insertion_sort_immutable.sml>>=and insert _ x[]=[x]

If the list is made of a first element `y`

and a tail `ys`

, one has to check whether `x`

is greater than `y`

. In this case is must be inserted later in the list. Otherwise, it is the first element of the new list.

<<insertion_sort_immutable.sml>>=| insert cmp x(l as y::ys)=casecmp(x, y)ofGREATER => y :: insert cmp x ys | _ => x :: l

### Testing

As before we use the toplevel to interactively test our code:

- insertion_sort Int.compare [5, 3, 1]; val it = [1,3,5] : int list - insertion_sort String.compare ["bob", "alice", "zoe", "barry"]; val it = ["alice","barry","bob","zoe"] : string list

Download code |