From 4d1c6ea551016c955f3377f19444eea2ad623bc4 Mon Sep 17 00:00:00 2001 From: Guy Ariely Date: Wed, 5 May 2021 12:24:42 +0300 Subject: [PATCH] fixed the merge implementation in MergeSort --- Sorts/MergeSort.js | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Sorts/MergeSort.js b/Sorts/MergeSort.js index b634704cf..102f33e7e 100644 --- a/Sorts/MergeSort.js +++ b/Sorts/MergeSort.js @@ -35,16 +35,19 @@ */ function merge (list1, list2) { - var results = [] + const results = [] + let i = 0 + let j = 0 - while (list1.length && list2.length) { - if (list1[0] <= list2[0]) { - results.push(list1.shift()) + while (i < list1.length && j < list2.length) { + if (list1[i] < list2[j]) { + results.push(list1[i++]) } else { - results.push(list2.shift()) + results.push(list2[j++]) } } - return results.concat(list1, list2) + + return results.concat(list1.slice(i), list2.slice(j)) } /**