From 8688d810f8f425a2dca93e1e902aa3eccd9af4f8 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Sun, 27 Dec 2020 22:44:32 +0200 Subject: [PATCH] Add mergesort --- snippets/mergeSort.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 snippets/mergeSort.md diff --git a/snippets/mergeSort.md b/snippets/mergeSort.md new file mode 100644 index 000000000..4c6e916e7 --- /dev/null +++ b/snippets/mergeSort.md @@ -0,0 +1,30 @@ +--- +title: mergeSort +tags: algorithm,array,recursion,advanced +--- + +Sorts an array of numbers, using the merge sort algorithm. + +- Use recursion. +- If the `length` of the array is less than `2`, return the array. +- Use `Math.floor()` to calculate the middle point of the array. +- Use `Array.prototype.slice()` to slice the array in two and recursively call `mergeSort()` on the created subarrays. +- Finally, use `Array.from()` and `Array.prototype.shift()` to combine the two sorted subarrays into one. + +```js +const mergeSort = arr => { + if (arr.length < 2) return arr; + const mid = Math.floor(arr.length / 2); + const l = mergeSort(arr.slice(0, mid)); + const r = mergeSort(arr.slice(mid, arr.length)); + return Array.from({ length: l.length + r.length }, () => { + if (!l.length) return r.shift(); + else if (!r.length) return l.shift(); + else return l[0] > r[0] ? r.shift() : l.shift(); + }); +}; +``` + +```js +mergeSort([5, 1, 4, 2, 3]); // [1, 2, 3, 4, 5] +```