# Algorithm Wiki

### Site Tools

This is an old revision of the document!

# Bubble sort

======= Algorithm ======= <syntax js> function insertSort(a) { for (var sortedN = 1; sortedN < a.length; sortedN++) { // Shift unsorted value downwards until it is sorted. for (var i = sortedN; i > 0 && a[i] < a[i-1]; i--) { swap(a, i, i-1); } } } </syntax> ======= Support ======= <syntax js> function swap(a, i, j) { var t = a[i]; a[i] = a[j]; a[j] = t; } function run(a) { insertSort(a); } </syntax> ======= Tests ======= <syntax js> </syntax> ======= Options ======= <syntax js> { "height": "270px" } </syntax> ======= Visualisation ======= <syntax html> <html> <head> <link rel="stylesheet" type="text/css" href="algorithms-lib/graph.css"/> <script src="http://d3js.org/d3.v2.js"></script> <script src="algorithms-lib/graph.js"></script> <script type="text/javascript"> var graph = new Graph(20); window.onload = function() { chart = graph.createGraph(d3.select("#chart")) } function args(forCloning) { return forCloning? graph.getClonableArray() : graph.array; } var lastUpdateDate = 0; function update(n, x, isRunning, duration, prev) { if (duration < 0) { return; // State-less visualisation. } if (x) { graph.drawGraph(duration, 0); var sortedN = x.lookupInScope("sortedN"); var idx = x.lookupInScope("i"); var bars = chart.selectAll("rect.data").data(graph.array, function(d) {return d.hash;}); // Increase the sorted section when we have an index being moved down. if (typeof idx !== "undefined") { sortedN++; } bars.classed("sorted", function(d, i) {return sortedN && i<sortedN}); // Unfortunate use of line numbers to highlight index being moved. if (!n || (n.lineno !== 4 && n.lineno !== 5)){ bars.classed("index", false); } else if (n.lineno === 5) { bars.classed("index", function(d, i) {return i===idx}); } } } </script> </head> <body> <div style="position:absolute;padding:2px"> <button onclick="graph.randomise(200)">Random</button> <button onclick="graph.randomise(5)">Few Unique</button> <button onclick="graph.almostSorted()">Almost sorted</button> <button onclick="graph.reverse()">Reverse</button> </div> <div id="chart"></div> </body> </html> </syntax>