You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
79 lines
1.7 KiB
79 lines
1.7 KiB
/**
|
|
*
|
|
*/
|
|
var Sorter = function() {};
|
|
Sorter.prototype.instructions = [];
|
|
|
|
// NOTE fisher-yates, http://bost.ocks.org/mike/algorithms/
|
|
/**
|
|
*
|
|
*/
|
|
Sorter.prototype.shuffle = function(arr) {
|
|
var n = arr.length, t, i;
|
|
while (n) {
|
|
i = Math.random() * n-- | 0; // 0 ≤ i < n
|
|
t = arr[n];
|
|
arr[n] = arr[i];
|
|
arr[i] = t;
|
|
}
|
|
return arr;
|
|
};
|
|
|
|
/**
|
|
*
|
|
*/
|
|
Sorter.prototype.addInstruction = function(operation, left, right, pivot) {
|
|
this.instructions.push({
|
|
operation: operation,
|
|
left: left,
|
|
right: right,
|
|
pivot: pivot
|
|
});
|
|
};
|
|
|
|
// NOTE adds to an instruction set
|
|
/**
|
|
*
|
|
*/
|
|
Sorter.prototype.quicksort = function(arr, start, end) {
|
|
if (end - start <= 0) {
|
|
this.addInstruction('single', start, end, null);
|
|
return this.visualizer;
|
|
}
|
|
|
|
var left = start;
|
|
var right = end;
|
|
|
|
var pivot = Math.floor((right + left) / 2);
|
|
var pivotval = arr[pivot].val;
|
|
var tmp;
|
|
|
|
this.addInstruction('init', left, right, pivot);
|
|
|
|
while (left <= right) {
|
|
while (arr[left].val < pivotval) {
|
|
left++;
|
|
this.addInstruction('inc-left', left, right, pivot);
|
|
}
|
|
|
|
while (arr[right].val > pivotval) {
|
|
right--;
|
|
this.addInstruction('dec-right', left, right, pivot);
|
|
}
|
|
|
|
if (left <= right) {
|
|
tmp = arr[left];
|
|
arr[left] = arr[right];
|
|
arr[right] = tmp;
|
|
|
|
this.addInstruction('swap', left, right, pivot);
|
|
|
|
left++;
|
|
right--;
|
|
this.addInstruction('swap-inc-dec', left, right, pivot);
|
|
}
|
|
}
|
|
|
|
this.quicksort(arr, start, right);
|
|
this.quicksort(arr, left, end);
|
|
};
|
|
|