【发布时间】:2021-12-30 04:29:25
【问题描述】:
我正在尝试观察我的递归合并排序,每一步都对数组进行切片。
function mergeSort(arr) {
if(arr.length === 1) return arr;
const mid = Math.floor(arr.length / 2);
const leftArray = arr.slice(0, mid);
const rightArray = arr.slice(mid, arr.length);
console.log(leftArray, rightArray)
return merge(mergeSort(leftArray), mergeSort(rightArray));
}
function merge(leftArray, rightArray) {
const sortedArray = [];
while(leftArray.length > 0 && rightArray.length > 0) {
if(leftArray[0] < rightArray[0]) {
sortedArray.push(leftArray[0]);
leftArray.shift();
} else {
sortedArray.push(rightArray[0]);
rightArray.shift();
}
}
return sortedArray.concat(leftArray).concat(rightArray);
}
如果您看到上面的代码,我正在记录 leftArray 和 rightArray。但是,一旦我运行代码,它就会立即记录每一步。为了控制代码执行,我将mergeSort 函数变成了一个生成器函数,这样每当我运行.next() 时,我就可以看到下一个切片。
function * mergeSort(arr) {
if(arr.length === 1) return arr;
const mid = Math.floor(arr.length / 2);
const leftArray = arr.slice(0, mid);
const rightArray = arr.slice(mid, arr.length);
yield console.log(leftArray, rightArray);
return merge(mergeSort(leftArray), mergeSort(rightArray));
}
function merge(leftArray, rightArray) {
const sortedArray = [];
while(leftArray.length > 0 && rightArray.length > 0) {
if(leftArray[0] < rightArray[0]) {
sortedArray.push(leftArray[0]);
leftArray.shift();
} else {
sortedArray.push(rightArray[0]);
rightArray.shift();
}
}
return sortedArray.concat(leftArray).concat(rightArray);
}
const list = [32, 12, 23, 52, 5, 16, 74, 21, 33, 55, 85];
const sort = mergeSort(list);
sort.next(); // I expected [32, 12], [23, 52, 5]
sort.next(); // [32, 12] and so on...
结果不是我所期望的。如果您对生成器功能的使用提出建议,我将不胜感激!
【问题讨论】:
-
如果你添加你得到的结果会很有帮助
-
如果你看第二个代码sn -p的最后2行,我写的是预期的结果。如果您需要更具体的示例,我会添加更多。
-
你使用了错误的语法生成器函数,不要使用返回
标签: javascript recursion generator