我目前正在尝试在 Javascript 中实现 mergeSort。我收到以下错误:
用户/stevenaguilar/Desktop/algorithms/merge/merge-sort.js:36 sort(a, lo, hi) { ^ RangeError: 最大调用堆栈大小在 Merge.sort (/Users/stevenaguilar/Desktop/algorithms/merge/合并-sort.js:36:7)
输入不是那么大,是一个包含 16 个元素的元素。
a = ["M", "E", "R", "G", "E", "S", "O", "R", "T", "E", "X", "A","M", "P", "L", "E"]
我能够使用 Ruby 创建合并排序,并且能够对数组进行排序。不知道为什么我在 JavaScript 中遇到上述错误,因为我在Node v14.0.0 这里运行的是合并排序的实现:
class Merge {
constructor() {
this.aux = []
}
sortPublic(a) {
this.sort(a, 0, a.length - 1);
}
merge(a, lo, mid, hi) {
let i = lo
let j = hi
var mid = mid + 1
for(let k = lo; k <= hi; k++) {
this.aux[k] = a[k]
}
for(let k = lo; k <= hi; k++) {
if(i > mid) {
a[k] = this.aux[j++]
}
else if(j > hi) {
a[k] = this.aux[i++]
}
else if(this.aux[j] < this.aux[i]) {
a[k] = this.aux[j++]
}
else {
a[k] = this.aux[i++]
}
}
}
sort(a, lo, hi) {
if(lo >= hi) { return; }
var mid = lo + (lo + hi) / 2
this.sort(a, lo, mid)
this.sort(a, mid + 1, hi)
this.merge(a, lo, mid, hi)
}
}
let mergeSort = new Merge;
console.log(mergeSort)
let a = ["M", "E", "R", "G", "E", "S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E"]
mergeSort.sortPublic(a);
这里有什么问题?
慕桂英4014372
相关分类