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.
73 lines
1.4 KiB
73 lines
1.4 KiB
/**
|
|
*
|
|
*/
|
|
var MergeSort = function() {
|
|
this.instructions = [];
|
|
};
|
|
|
|
MergeSort.prototype = Object.create(Sorter.prototype);
|
|
|
|
/**
|
|
*
|
|
*/
|
|
MergeSort.prototype.addInstruction = function(operation, left, right, mid) {
|
|
// console.log({
|
|
// operation: operation,
|
|
// left: left,
|
|
// right: right,
|
|
// mid: mid
|
|
// });
|
|
|
|
this.instructions.push({
|
|
operation: operation,
|
|
left: left,
|
|
right: right
|
|
});
|
|
};
|
|
|
|
/**
|
|
*
|
|
*/
|
|
MergeSort.prototype.sort = function(arr, start, end) {
|
|
if (arr.length === 0) {
|
|
return arr;
|
|
}
|
|
|
|
if (start === end) {
|
|
this.addInstruction('single', start);
|
|
return new Array(arr[start]);
|
|
}
|
|
|
|
var mid = start + Math.floor((end - start) / 2);
|
|
|
|
var arr1 = this.sort(arr, start, mid);
|
|
var arr2 = this.sort(arr, mid + 1, end);
|
|
|
|
var result = this.merge(arr1, arr2);
|
|
|
|
return result;
|
|
};
|
|
|
|
/**
|
|
*
|
|
*/
|
|
MergeSort.prototype.merge = function(arr1, arr2) {
|
|
var result = [];
|
|
|
|
while (arr1.length > 0 || arr2.length > 0) {
|
|
if (arr1.length === 0) {
|
|
result.push(arr2.shift());
|
|
}
|
|
else if (arr2.length === 0) {
|
|
result.push(arr1.shift());
|
|
}
|
|
else if (arr1[0].value <= arr2[0].value) {
|
|
result.push(arr1.shift());
|
|
}
|
|
else {
|
|
result.push(arr2.shift());
|
|
}
|
|
}
|
|
|
|
return result;
|
|
};
|
|
|