D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
bhvaleri
Full window
Github gist
Quicksort on a line
<!doctype html> <html> <style> .line { fill: none; stroke: steelblue; stroke-width: 1.5px; } circle { stroke: steelblue; stroke-width: 1.5px; } </style> <body> <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script> <script> var width = 960, height = 500; var count = 1000; var svg = d3.select('body').append('svg') .attr('width', width) .attr('height', height); var line = d3.svg.line(); line.interpolate('cardinal'); points = d3.range(1, count).map(function(i) { return [i * width / count, Math.round(50 + Math.random() * (height - 100))]; }); draw = function () { /* var circle = svg.selectAll('circle') .data(points); circle.enter().append('circle') .attr('r', 6.5); circle.attr('cx', function(d) { return d[0]; }) .attr('cy', function(d) { return d[1]; }); */ var path = svg.selectAll('path') .data([points]); path.enter().append('path') .attr('class', 'line') path.attr('d', line); } quicksort = function (array) { var actions = []; function partition(left, right, pivot) { var v = array[pivot]; swap(pivot, --right); for (var i = left; i < right; ++i) if (array[i] <= v) swap(i, left++); swap(left, right); return left; } function swap(i, j) { var t = array[i]; array[i] = array[j]; array[j] = t; actions.push({type: "swap", i: i, j: j}); } function recurse(left, right) { if (left < right) { var pivot = left + ~~(Math.random() * (right - left)); actions.push({type: "partition", pivot: pivot}); pivot = partition(left, right, pivot); recurse(left, pivot); recurse(pivot + 1, right); } } recurse(0, array.length); return actions; } sort = function () { pointsToSort = points.map(function (point) { return point[1]; }); actions = quicksort(pointsToSort).reverse(); function step() { setInterval(function () { var action = actions.pop(); if (action) switch (action.type) { case "partition": { step(); break; } case "swap": { var t = points[action.i][1]; points[action.i][1] = points[action.j][1]; points[action.j][1] = t; draw(); break; } } }, 100); }; step(); } sort(); </script> </html>
Modified
http://d3js.org/d3.v3.min.js
to a secure url
https://d3js.org/d3.v3.min.js