From 595f97ee04874159806ef8656dd167f071cf82f9 Mon Sep 17 00:00:00 2001 From: yigencong Date: Sun, 25 Feb 2024 16:31:55 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E5=BD=92=E5=B9=B6?= =?UTF-8?q?=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sort/merge-sort.mjs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 sort/merge-sort.mjs diff --git a/sort/merge-sort.mjs b/sort/merge-sort.mjs new file mode 100644 index 0000000..c51964e --- /dev/null +++ b/sort/merge-sort.mjs @@ -0,0 +1,42 @@ +/** + * @description 不修改原数组,返回新数组 + * @param {number[]} left - 需要合并的左数组 + * @param {number[]} right - 需要合并的右数组 + */ + export function mergeSort(arr) { + if (arr.length <= 1) { + return arr; // 已经有序 + } + + // 分解 + const middle = Math.floor(arr.length / 2); + const left = arr.slice(0, middle); + const right = arr.slice(middle); + + // 递归地对左右两部分进行归并排序 + const sortedLeft = mergeSort(left); + const sortedRight = mergeSort(right); + + // 合并 + return merge(sortedLeft, sortedRight); +} + +function merge(left, right) { + let result = []; + let leftIndex = 0; + let rightIndex = 0; + + // 比较两个数组的元素,将较小的元素加入结果数组 + while (leftIndex < left.length && rightIndex < right.length) { + if (left[leftIndex] < right[rightIndex]) { + result.push(left[leftIndex]); + leftIndex++; + } else { + result.push(right[rightIndex]); + rightIndex++; + } + } + + // 将剩余的元素加入结果数组 + return result.concat(left.slice(leftIndex), right.slice(rightIndex)); +}