Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
JavaScript to be used with ScriptCraft to create static sorting algorithm visualizations in Minecraft.
load($SCRIPT_DIR + "/../drone.js");
var arr = [{i:1,b:'35:1'},{i:5,b:'35:5'},{i:3,b:'35:3'},{i:2,b:'35:2'},{i:4,b:'35:4'},{i:7,b:'35:7'},{i:8,b:'35:8'},
{i:6,b:'35:6'},{i:0,b:35},{i:14,b:'35:14'},{i:13,b:'35:13'},{i:12,b:'35:12'},{i:10,b:'35:10'},{i:9,b:'35:9'},{i:11,b:'35:11'}];
var render = function(a,d){
d.up(a.length);
for(var k =0;k< a.length;k++){
d.box(a[k].b).down();
}
d.left();
}
Drone.extend('bubble',function(){
var d = new Drone();
var c = arr.slice(0);
render(c,d);
// Bubblesort
// taken from http://www.codecodex.com/wiki/Bubble_sort#JavaScript
var bubblesort = function(){
var swapped;
var swap = function(j, k) {
var temp = c[j];
c[j] = c[k];
c[k] = temp;
return(true);
}
for(var i=1; i<c.length; i++) {
swapped = false;
for(var j=0; j<c.length - i; j++) {
if (c[j+1].i < c[j].i) {
swapped = swap(j, j+1);
}
render(c,d);
}
if (!swapped) break;
}
}
bubblesort();
return this;
});
Drone.extend('shell',function(){
var d = new Drone();
var c = arr.slice(0);
render(c,d);
// Shell Sort
// taken from http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort#JavaScript
function shellSort () {
for (var h = c.length; h = parseInt(h / 2);) {
for (var i = h; i < c.length; i++) {
var k = c[i];
for (var j = i; j >= h && k.i < c[j - h].i; j -= h){
c[j] = c[j - h];
}
c[j] = k;
render(c,d);
}
}
}
shellSort();
return this;
});
Drone.extend('quick',function(){
var d = new Drone();
var c = arr.slice(0);
render(c,d);
// Quicksort
// taken from http://rosettacode.org/wiki/Sorting_algorithms/Quicksort#JavaScript
function sort(array, less) {
function swap(i, j) { var t=array[i]; array[i]=array[j]; array[j]=t }
function quicksort(left, right) {
if (left < right) {
var pivot = array[(left + right) >> 1];
var left_new = left, right_new = right;
do {
while (less(array[left_new], pivot))
left_new++;
while (less(pivot, array[right_new]))
right_new--;
if (left_new <= right_new){
swap(left_new++, right_new--);
render(array,d);
}
} while (left_new <= right_new);
quicksort(left, right_new);
quicksort(left_new, right);
}
}
quicksort(0, array.length-1);
return array;
}
c = sort(c,function(a,b){
return a.i < b.i;
});
return this;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment