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.
84 lines
2.3 KiB
84 lines
2.3 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', true, end)
|
|
// .instruct('message1', true, 'Start: ' + start)
|
|
// .instruct('message2', true, '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('marker1', true, left, 'L')
|
|
.instruct('marker2', true, right, 'R');
|
|
// .instruct('unhighlight')
|
|
// .instruct('highlight', true, pivot)
|
|
// .instruct('message3', false, 'Pivot value: ' + pivotval);
|
|
|
|
while (left <= right) {
|
|
while (arr[left].value < pivotval) {
|
|
left++;
|
|
|
|
this.comparisons++;
|
|
this.instruct('marker1', true, left)
|
|
.instruct('message1', false, 'Left: ' + left)
|
|
.instruct('stats1', false, 'Comparisons: ' + this.comparisons)
|
|
}
|
|
|
|
while (arr[right].value > pivotval) {
|
|
right--;
|
|
|
|
this.comparisons++;
|
|
this.instruct('marker2', true, right)
|
|
.instruct('message2', false, 'Right: ' + right)
|
|
.instruct('stats1', false, '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', false, 'Swaps: ' + this.swaps)
|
|
.instruct('message1', false, 'Left: ' + left)
|
|
.instruct('message2', false, 'Right: ' + right)
|
|
.instruct('marker1', true, left)
|
|
.instruct('marker2', true, right);
|
|
}
|
|
}
|
|
|
|
this.sort(arr, start, right);
|
|
this.sort(arr, left, end);
|
|
|
|
return arr;
|
|
};
|
|
|