Skip to content

Instantly share code, notes, and snippets.

@bhvaleri
Created April 14, 2014 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhvaleri/10687912 to your computer and use it in GitHub Desktop.
Save bhvaleri/10687912 to your computer and use it in GitHub Desktop.
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="http://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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment