Skip to content

Commit 46d009b

Browse files
committed
fix mege sort issues with duplicates
1 parent f738510 commit 46d009b

File tree

2 files changed

+4
-4
lines changed

2 files changed

+4
-4
lines changed

src/algorithms/sorting/merge-sort.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
function merge(array1, array2 = []) {
22
const mergedLength = array1.length + array2.length;
3-
const mergedArray = [];
3+
const mergedArray = Array(mergedLength);
44

55
for (let index = 0, i1 = 0, i2 = 0; index < mergedLength; index += 1) {
6-
if (i2 >= array2.length || (i1 < array1.length && array1[i1] < array2[i2])) {
6+
if (i2 >= array2.length || (i1 < array1.length && array1[i1] <= array2[i2])) {
77
mergedArray[index] = array1[i1];
88
i1 += 1;
9-
} else if (i1 >= array1.length || (i2 < array2.length && array2[i2] < array1[i1])) {
9+
} else if (i1 >= array1.length || (i2 < array2.length && array2[i2] <= array1[i1])) {
1010
mergedArray[index] = array2[i2];
1111
i2 += 1;
1212
}

src/algorithms/sorting/sorting.spec.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ sortingAlgorithms.forEach((sort) => {
3535
expect(sort(new Set([3, 1, 2]))).toEqual([1, 2, 3]);
3636
});
3737

38-
xit('should sort with duplicated values', () => {
38+
it('should sort with duplicated values', () => {
3939
expect(sort([1, 3, 2, 1])).toEqual([1, 1, 2, 3]);
4040
});
4141
});

0 commit comments

Comments
 (0)