User Tools

Site Tools


λ Bubble sort

======= Algorithm ======= <syntax js> function bubbleSort(a) { var swapped; do { swapped = false; for (var i=0, c=a.length-1; i<c; i++) { // If items are out of order swap them. if (a[i] > a[i+1]) { swap(a, i, i+1); swapped = true; } } } while(swapped); return a; } </syntax> ======= Support ======= <syntax js> function swap(a, i, j) { var t = a[i]; a[i] = a[j]; a[j] = t; } function run(a) { bubbleSort(a); } </syntax> ======= Tests ======= <syntax js> </syntax> ======= Options ======= <syntax js> { "title":"Bubble sort", "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 oldI; function update(n, x, isRunning, duration, prev) { if (duration < 0) { return; // State-less visualisation. } if (x) { graph.drawGraph(duration); var idx = x.lookupInScope("i"); var bars = chart.selectAll("rect.data").data(graph.array, function(d) {return d.hash;}); if (idx !== oldI) { bars.classed("index", function(d, i) {return i===idx}); oldI = 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>

algorithm/bubble_sort.txt · Last modified: 2015/02/02 08:28 (external edit)