# λ Selection sort

======= Algorithm ======= <syntax js> function selectionSort(a) { for (var j = 0; j < a.length-1; j++) { // Find the min element in the unsorted range a[j .. n-1] var iMin = j; for (var i = j+1; i < a.length; i++) { // If a[i] is a new minimum, remember the minimum index. if (a[i] < a[iMin]) { iMin = i; } } // Swap the min value to the beginning of the range. swap(a, j, iMin); } 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) { selectionSort(a); } </syntax> ======= Tests ======= <syntax js> </syntax> ======= Options ======= <syntax js> { "title": "Selection sort", "height":"270px" } </syntax> ======= Visualisation ======= <syntax html> <html> <head> <style type='text/css'> .chart rect { fill: steelblue; notstroke: white; } .chart rect.min { fill: pink; } .chart rect.sorted { fill: lightsteelblue; } .chart rect.index { fill: red; } </style> <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, oldMin; function update(n, x, isRunning, duration, prev) { if (duration < 0) { return; // State-less visualisation. } if (x) { graph.drawGraph(duration); var sortedN = x.lookupInScope("sortedN"); var idx = x.lookupInScope("i"); var iMin = x.lookupInScope("iMin"); 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}); if (idx !== oldI) { bars.classed("index", function(d, i) {return i===idx}); oldI = idx; } if (iMin !== oldMin) { bars.classed("min", function(d, i) {return i===iMin}); oldMin = iMin; } } } </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>