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.
 
 
 

53 lines
1.0 KiB

/**
*
*/
var MergeSort = function() {};
MergeSort.prototype = Object.create(Sorter.prototype);
/**
*
*/
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;
};