Skip to content

Commit 4d1c6ea

Browse files
committed
fixed the merge implementation in MergeSort
1 parent 1f23206 commit 4d1c6ea

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

Sorts/MergeSort.js

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,19 @@
3535
*/
3636

3737
function merge (list1, list2) {
38-
var results = []
38+
const results = []
39+
let i = 0
40+
let j = 0
3941

40-
while (list1.length && list2.length) {
41-
if (list1[0] <= list2[0]) {
42-
results.push(list1.shift())
42+
while (i < list1.length && j < list2.length) {
43+
if (list1[i] < list2[j]) {
44+
results.push(list1[i++])
4345
} else {
44-
results.push(list2.shift())
46+
results.push(list2[j++])
4547
}
4648
}
47-
return results.concat(list1, list2)
49+
50+
return results.concat(list1.slice(i), list2.slice(j))
4851
}
4952

5053
/**

0 commit comments

Comments
 (0)