I'm attempting to build out a monkey-patched version of mergeSort
but I'm running into errors every single time. I've ran through debugger a few times and it looks like everything is sorting properly until the last step where I jump to a line in a loader.js file.
Can anyone help me check this out? Thanks in advance!
Array.prototype.mergeSort = function(callback) {
if (this.length <= 1) return this;
if (!callback) {
callback = function(x, y) {
if (x > y) return -1;
else if (x < y) return 1;
else return 0;
};
}
const mid = Math.floor(this.length / 2);
const sortedLeft = this.slice(0, mid).mergeSort(callback);
const sortedRight = this.slice(mid).mergeSort(callback);
return sortedLeft.merge(sortedRight, callback);
};
Array.prototype.merge = function(arr, callback) {
let merged = [];
while (this.length > 0 || arr.length > 0) {
if (callback(this[0], arr[0]) < 0) {
merged.push(arr.shift());
break;
} else if (callback(this[0], arr[0]) >= 0) {
merged.push(this.shift());
break;
}
}
merged = merged.concat(this);
merged = merged.concat(arr);
return merged;
};
答案 0 :(得分:2)
当任一列表为空时,合并循环应停止:您应该输入{p>而不是while (this.length > 0 || arr.length > 0)
while (this.length > 0 && arr.length > 0)
此外,每次存储到break
数组后,您都不应从循环中merge
,并且将元素进行两次比较是多余的。
这是更正的版本:
Array.prototype.merge = function(arr, callback) {
let merged = [];
while (this.length > 0 && arr.length > 0) {
if (callback(this[0], arr[0]) < 0) {
merged.push(arr.shift());
} else {
merged.push(this.shift());
}
}
merged = merged.concat(this);
return merged.concat(arr);
};
但是请注意,您的merge
方法按降序对数组进行排序,默认的callback
函数也按降序对元素进行比较,从而导致数组按巧合顺序按升序进行排序。您可能想要简化此过程,并在null
中接受merge
回调函数。
这是一个更通用的版本:
Array.prototype.mergeSort = function(callback) {
if (this.length <= 1)
return this;
const mid = this.length >> 1;
const sortedLeft = this.slice(0, mid).mergeSort(callback);
const sortedRight = this.slice(mid).mergeSort(callback);
return sortedLeft.merge(sortedRight, callback);
};
Array.prototype.merge = function(arr, callback) {
let merged = [];
if (callback) {
while (this.length > 0 && arr.length > 0) {
if (callback(this[0], arr[0]) <= 0) {
merged.push(this.shift());
} else {
merged.push(arr.shift());
}
}
} else {
while (this.length > 0 && arr.length > 0) {
if (this[0] <= arr[0]) {
merged.push(this.shift());
} else {
merged.push(arr.shift());
}
}
}
return merged.concat(this).concat(arr);
};