/** * */ var InsertionSort = function() { //===== Action management. // this.preSort = function(arr) { 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, ``) .instruct(Itemgroup.message, 0, 0, 4, ``) .instruct(Itemgroup.message, 0, 100, 5, `Starting sort.`) }; // this.midSort = function(arr, i, j) { 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 - 1), (j - 1), Visualizer.bg1) .instruct(Itemgroup.message, 0, 0, 1, `Comparisons: ${this.comparisons}`) .instruct(Itemgroup.message, 0, 0, 4, `Comparing [${j - 1}] and [${j}]`) .instruct(Itemgroup.message, 0, 100, 5, ``) }; // this.swap = function(arr, j) { this .instruct(Itemgroup.message, 0, 0, 2, `Swaps: ${this.swaps}`) .instruct(Itemgroup.message, 0, 0, 5, `${arr[j]} < ${arr[j - 1]}, swapped.`) .instruct(Itemgroup.swap, 1, 300, j - 1, j) if (j - 1 > 0) { this.instruct(Itemgroup.message, 0, 0, 3, `Continuing downstream...`) } else { this.instruct(Itemgroup.message, 0, 0, 3, ``) } }; // this.postSort = function(arr) { 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, ``) .instruct(Itemgroup.message, 0, 0, 4, ``) .instruct(Itemgroup.message, 0, 100, 5, `Sorting complete.`) }; }; InsertionSort.prototype = Object.create(Sorter.prototype); /** * */ InsertionSort.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) }; /** * */ InsertionSort.prototype.sort = function(arr) { var len = arr.length; var i; var j; var tmp; this.preSort(arr); for (i = 0; i < len; i++) { for (j = i; j > 0; j--) { this.comparisons++; this.midSort(arr, i, j); if (arr[j - 1] > arr[j]) { this.swaps++; tmp = arr[j - 1]; arr[j - 1] = arr[j]; arr[j] = tmp; this.swap(arr, j); } else { break; } } } this.postSort(arr); return arr; };