Insertion sort (Standard ML)

From LiteratePrograms

Jump to: navigation, search
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.


Sorting in place


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:

fun insertion_sort cmp a =
  Array.appi (fn (i, v) =>
    insert v into sorted sublist)

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 *)
  val j = ref (i - 1)
  while !j >= 0 andalso cmp (Array.sub (a, !j), v) = GREATER do (
    Array.update (a, !j + 1, Array.sub (a, !j));
    j := !j - 1
  Array.update (a, !j + 1, v)

You must be aware that the average and worse case time complexity of insertion_sort a are O(N2) where N = Array.length a hence it is not recommended in practice (use a O(NlogN) algorithm instead).


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):

- val a = Array.fromList [5, 3, 1];
val a = [|5,3,1|] : int array
- insertion_sort a;
val it = () : unit
- a;
val it = [|1,3,5|] : int array

Sorting immutable lists


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:

fun insertion_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 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:

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.

  | insert cmp x (l as y::ys) =
      case cmp (x, y) of GREATER => y :: insert cmp x ys
                       | _       => x :: l


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

- insertion_sort [5, 3, 1];
val it = [1,3,5] : int list
- insertion_sort ["bob", "alice", "zoe", "barry"];
val it = ["alice","barry","bob","zoe"] : string list
Download code