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.
 
 
 

121 lines
3.5 KiB

/**
*
*/
var InsertionSort = function() {
var _this = this;
this.ui = {
presort: function presort(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.`)
},
//
midsort: function midsort(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, ``)
},
//
swap: function swap(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, ``)
}
},
//
postsort: function postsort(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.ui.presort(arr);
for (i = 0; i < len; i++) {
for (j = i; j > 0; j--) {
this.comparisons++;
this.ui.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.ui.swap(arr, j);
}
else {
break;
}
}
}
this.ui.postsort(arr);
return arr;
};