/** * */ var ShellSort = function() { //===== Action management. // this.preSort = function(arr, i, gap) { this .instruct(Itemgroup.background, 1, 0, 0, arr.length, Visualizer.bg0) .instruct(Itemgroup.message, 0, 0, 1, `Comparisons: ${this.comparisons}`) .instruct(Itemgroup.message, 0, 0, 2, `Swaps: ${this.swaps}`) .instruct(Itemgroup.message, 0, 0, 3, `Gap: ${gap}`) .instruct(Itemgroup.message, 0, 0, 4, ``) .instruct(Itemgroup.message, 0, 100, 5, `Starting sort at index ${i}.`) }; // this.midSort = function(arr, i, j, gap) { this .instruct(Itemgroup.background, 1, 0, 0, arr.length, Visualizer.bg0) .instruct(Itemgroup.background, 1, 0, j, j, Visualizer.bg1) .instruct(Itemgroup.background, 1, 0, (j - gap), (j - gap), Visualizer.bg1) .instruct(Itemgroup.message, 0, 0, 4, `Comparing [${j - gap}] and [${j}]`) .instruct(Itemgroup.message, 0, 100, 5, ``) }; // this.swap = function(arr, j, gap) { this .instruct(Itemgroup.message, 0, 100, 4, `${arr[j]} < ${arr[j - gap]}, swap required.`) .instruct(Itemgroup.swap, 1, 300, j - gap, j) if (j - gap > 0) { this .instruct(Itemgroup.message, 0, 100, 5, `Continuing downstream...`) } }; // this.noswap = function(arr, j, gap) { this .instruct(Itemgroup.message, 0, 0, 4, `${arr[j]} > ${arr[j - gap]}, no swap required.`) .instruct(Itemgroup.message, 0, 100, 5, ``) }; // this.postSort = function(arr) { this .instruct(Itemgroup.background, 1, 0, 0, arr.length, Visualizer.bg0) .instruct(Itemgroup.message, 0, 0, 3, ``) .instruct(Itemgroup.message, 0, 0, 4, ``) .instruct(Itemgroup.message, 0, 100, 5, `Ready for insertion sort.`) }; }; ShellSort.prototype = Object.create(Sorter.prototype); /** * */ ShellSort.prototype.init = function() { var len = this.shuffled.length; this.actions = []; this.swaps = 0; this.comparisons = 0; this .instruct(Itemgroup.items, 0, 0, len) .instruct(Itemgroup.items, 1, 0, len) .instruct(Itemgroup.items, 2, 0, len) for (var i = 0; i < len; i++) { this.instruct(Itemgroup.text, 1, 0, i, this.shuffled[i]); } this .instruct(Itemgroup.foreground, 1, 0, 0, len, Visualizer.fg0) .instruct(Itemgroup.background, 1, 0, 0, len, Visualizer.bg0) .instruct(Itemgroup.opacity, 0, 0, 0, len, 0) .instruct(Itemgroup.opacity, 2, 0, 0, len, 0) }; /** * */ ShellSort.prototype.sort = function(arr) { var len = arr.length; var gap = Math.floor(len / 3); var i, j; for (i = 0; i < gap; i++) { this.preSort(arr, i, gap); this.gapSort(arr, i, gap); } this.postSort(arr); return arr; }; /** * */ ShellSort.prototype.gapSort = function(arr, start, gap) { var i, j; var len = arr.length; for (i = start; i < len; i += gap) { for (j = i; j > start; j -= gap) { this.midSort(arr, i, j, gap); this.comparisons++; if (arr[j - gap] > arr[j]) { this.swaps++; tmp = arr[j - gap]; arr[j - gap] = arr[j]; arr[j] = tmp; this.swap(arr, j, gap); } else { this.noswap(arr, j, gap); break; } } } };