Merge Sort可正常排序日期但无法正确排序整数值的问题求解
归并排序整数排序失效修复
你的代码存在两个核心逻辑错误,导致整数排序结果乱序:
- 长度为2的子数组排序分支完全失效:判断条件不成立时没有交换元素位置,无论两个元素的大小关系如何,都返回原顺序的数组,导致归并依赖的基础有序子数组构建错误。日期类型排序看似正常只是巧合:ISO格式日期字符串的字典序和时间序一致,测试时未刚好命中二元逆序子数组的场景。
- 边界判断不全:仅处理了长度为1的数组,传入空数组会触发无限递归导致栈溢出。
- 合并逻辑存在冗余判断:
else if (valueTwo < valueOne)是多余分支,valueOne <= valueTwo不成立时必然满足该条件,可以直接简化为else。
修复后完整代码
function sortBy(array, key, descending = false) { const length = array.length; // 处理空数组、单元素数组的边界场景 if (length <= 1) { return array; } else if (length === 2) { const aValue = array[0][key]; const bValue = array[1][key]; // 二元数组升序排列,逆序时交换元素 if (aValue <= bValue) { return array; } return [array[1], array[0]]; } const mid = Math.floor(length / 2); const firstHalf = array.slice(0, mid); const secondHalf = array.slice(mid, length); // 递归时无需传入descending,所有子数组统一按升序排列,最终顶层统一反转 const arrayOne = sortBy(firstHalf, key); const arrayTwo = sortBy(secondHalf, key); const merged = []; while (arrayOne.length || arrayTwo.length) { if (!arrayOne.length) { merged.push(arrayTwo.shift()); continue; } if (!arrayTwo.length) { merged.push(arrayOne.shift()); continue; } const valueOne = arrayOne[0][key]; const valueTwo = arrayTwo[0][key]; if (valueOne <= valueTwo) { merged.push(arrayOne.shift()); } else { merged.push(arrayTwo.shift()); } } return descending ? merged.reverse() : merged; }
调用方式
要实现帖子按votes字段从高到低排序,直接传入第三个参数为true即可:
const sortedPosts = sortBy(postList, 'votes', true);
内容的提问来源于stack exchange,提问作者Colton Van Bastelaere
相关产品推荐
相关产品推荐

