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.
 
 
 

81 lines
2.0 KiB

/**
*
*/
var QuickSort = function() {
this.instructions = [];
this.swaps = 0;
this.comparisons = 0;
};
QuickSort.prototype = Object.create(Sorter.prototype);
QuickSort.prototype.instruct = function() {
this.instructions.push(arguments);
return this;
};
// NOTE adds to an instruction set
/**
*
*/
QuickSort.prototype.sort = function(arr, start, end) {
if (end - start <= 0) {
this.instruct('highlight', end)
.instruct('message1', 'Start: ' + start)
.instruct('message2', 'End: ' + end)
return arr;
}
var left = start;
var right = end;
var pivot = Math.floor((right + left) / 2);
var pivotval = arr[pivot].value;
var tmp;
this.instruct('initSection', left, right)
.instruct('highlight', pivot)
.instruct('message3', 'Pivot value: ' + pivotval);
while (left <= right) {
while (arr[left].value < pivotval) {
left++;
this.comparisons++;
this.instruct('marker1', left, 'Left')
.instruct('message1', 'Left: ' + left)
.instruct('stats1', 'Comparisons: ' + this.comparisons)
}
while (arr[right].value > pivotval) {
right--;
this.comparisons++;
this.instruct('marker2', right, 'Right')
.instruct('message2', 'Right: ' + right)
.instruct('stats1', 'Comparisons: ' + this.comparisons)
}
if (left <= right) {
tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left++;
right--;
this.swaps++;
this.instruct('swap', left, right)
.instruct('stats2', 'Swaps: ' + this.swaps)
.instruct('message1', 'Left: ' + left)
.instruct('message2', 'Right: ' + right)
.instruct('marker1', left)
.instruct('marker2', right);
}
}
this.sort(arr, start, right);
this.sort(arr, left, end);
return arr;
};