/** * */ var QuickSort = function(VisualizerInstance) { this.swaps = 0; this.comparisons = 0; this.V = VisualizerInstance; this.V .instruct(this.V.hideMarker, 0, 1) .instruct(this.V.hideMarker, 0, 2) .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) { // message: Left and Right have crossed, start sorting sublists. 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.fade, 0, -1, start - 1) .instruct(this.V.fade, 0, end + 1, arr.length) // Message: pivot chosen .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) .instruct(this.V.marker, 100, 2, right); right--; } this.V .instruct(this.V.message, 0, 5, `Right stop: ${arr[right].value} <= ${pivotval} `) .instruct(this.V.marker, 100, 2, right); if (left <= right) { tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp; this.V.instruct(this.V.swap, 100, 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.unfade, 0) .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; };