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.
 
 
 

115 lines
3.3 KiB

/**
*
*/
var QuickSort = function(Visualizer) {
this.swaps = 0;
this.comparisons = 0;
this.V = Visualizer;
this.V
.instruct(this.V.message, 0, 2, 'Swaps: ' + this.swaps)
.instruct(this.V.message, 0, 1, 'Comparisons: ' + this.comparisons);
};
QuickSort.prototype = Object.create(Sorter.prototype);
// NOTE adds to an instruction set
/**
*
*/
QuickSort.prototype.sort = function(arr, start, end) {
if (end - start <= 0) {
// this//.instruct(this.V.highlight, 500, end)
// .instruct(this.V.message, 0, 3, 'Start: ' + start)
// .instruct(this.V.message, 0, 4, 'End: ' + end)
return arr;
}
var left = start;
var right = end;
var pivot = Math.floor((right + left) / 2);
var pivotval = arr[pivot].value;
var tmp;
var rval;
this.V
.instruct(this.V.marker, 0, 1, left, 'L')
.instruct(this.V.marker, 0, 2, right, 'R')
.instruct(this.V.showMarker, 0, 1)
.instruct(this.V.showMarker, 0, 2)
.instruct(this.V.unhighlight, 0)
.instruct(this.V.highlight, 0, pivot)
.instruct(this.V.message, 0, 3, 'Sorting from [' + start + '] to [' + end + ']')
.instruct(this.V.message, 0, 4, '')
.instruct(this.V.message, 100, 5, '');
while (left <= right) {
this.V.instruct(this.V.message, 0, 4, '');
this.V.instruct(this.V.message, 0, 5, '');
while (arr[left].value < pivotval) {
this.comparisons++;
this.V
.instruct(this.V.message, 0, 4, `${arr[left].value} < ${pivotval}, increment left` )
.instruct(this.V.message, 0, 1, `Comparisons: ${this.comparisons}`)
.instruct(this.V.marker, 500, 1, left);
left++;
}
this.V
.instruct(this.V.message, 0, 4, `Left stop: ${arr[left].value} >= ${pivotval}`)
.instruct(this.V.marker, 500, 1, left);
while (arr[right].value > pivotval) {
this.comparisons++;
this.V
.instruct(this.V.message, 0, 5, `${arr[right].value} < ${pivotval}, decrement right`)
.instruct(this.V.message, 0, 1, 'Comparisons: ' + this.comparisons)
right--;
this.V.instruct(this.V.marker, 500, 2, right)
}
this.V.instruct(this.V.message, 100, 5, `Right stop: ${arr[right].value} <= ${pivotval} `)
if (left <= right) {
tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
this.V.instruct(this.V.swap, 500, left, right);
left++;
right--;
this.swaps++;
this.V
.instruct(this.V.message, 0, 2, 'Swaps: ' + this.swaps)
.instruct(this.V.message, 0, 4, 'Incremement left...')
.instruct(this.V.message, 0, 5, 'Decrement right...')
.instruct(this.V.marker, 100, 1, left)
.instruct(this.V.marker, 100, 2, right)
}
}
this.V
.instruct(this.V.unhighlight, 0)
.instruct(this.V.hideMarker, 0, 1)
.instruct(this.V.hideMarker, 0, 2)
.instruct(this.V.message, 0, 3, 'Sorting complete.')
.instruct(this.V.message, 0, 4, '')
.instruct(this.V.message, 0, 5, '');
this.sort(arr, start, right);
this.sort(arr, left, end);
return arr;
};