User Tools

Site Tools

This is an old revision of the document!

An algorithm is stored in a single page in the Algorithm namespace. Different variants require different pages. For example Factorial recursive and Factorial iterative.

Including an algorithm in a page

You include an algorithm on a different page using the algorithm tag. The title attribute is set to the title of the algorithm page. <pre> <algorithm title=“Fisher-Yates shuffle” height=200></algorithm> </pre>

This transcludes the algorithm from Fisher-Yates shuffle.

Creating an algorithm page

An algorithm page is split into three sections:

====== Algorithm ======
====== Support ======
====== Visualisation ======

Each of these sections contains code wrapped in &lt;code&gt; tags.


The 1st section contains the algorithm. This is the code that the user sees in the interactive environment.

function shuffle(a) {
    for (var i=a.length-1; i>0; i--) {
        var j = Math.floor(Math.random()*(i+1)); // j random integer [0-i]
        swap(a, j, i);
    return a;


The 2nd section contains the support code. This is support code, such as functions that the main algorithm uses. If it also includes a run() function this function is called when running the algorithm.

function swap(a, i, j) {
    var t = a[i]; a[i] = a[j]; a[j] = t;
a = [1,2,3,4,5,6,7,8,9,0];
function run() {
    return shuffle(a);


The 3rd section contains the visualisation code. This is a complete webpage that contains an update() function, which is called for every new line when running the algorithm. The update function takes two arguments, the current node in the AST and an execution context.

    <script type="text/javascript">
        function update(n, x) {
            var element = document.getElementById("container");
            var i = x.lookupInScope("i");
            var j = x.lookupInScope("j");
            var a = x.lookupInScope("a");
            var xValue = x.lookupInScope("x");
            if (i) {
               var arrayString = "[";
               for (var k=0; k<a.length;k++) {
                   arrayString += i===k? "<span style=\"color:red\">"+a[k]+"</span>" : j===k? "<span style=\"color:blue\">"+a[k]+"</span>" : a[k];
                   if (k < a.length-1) arrayString += ", ";
               arrayString += "]";
               element.innerHTML = "a = " + arrayString + "<br>"+"i = "+i;
  <pre id="container"></pre>
creating_an_algorithm.1346527703.txt.gz · Last modified: 2015/02/02 08:24 (external edit)