Skip to content

Commit cf7237b

Browse files
committed
refactor mergeSort
1 parent b6d9c5f commit cf7237b

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

src/algorithms/mergeSort.js

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ import { insertStep } from './helpers';
22

33
function mergeSort(array, position, arraySteps, colorSteps) {
44
if (array.length === 1) return array;
5+
let mid = Math.floor(array.length / 2);
56

6-
let mid = array.length / 2;
7-
7+
// Split and work recursively
88
let arrayA = mergeSort(array.slice(0, mid), position, arraySteps, colorSteps);
99
let arrayB = mergeSort(array.slice(mid), position + mid, arraySteps, colorSteps);
1010

@@ -24,30 +24,28 @@ const merge = (arrayA, arrayB, position, arraySteps, colorSteps) => {
2424
arrayNew.push(arrayB.shift());
2525
insertStep(arrayNew, position, arraySteps);
2626
}
27-
28-
if (position === 0) {
29-
let colorKey = colorSteps[colorSteps.length - 1].slice();
30-
colorKey[arrayNew.length - 1] = true;
31-
colorSteps.push(colorKey);
32-
} else {
33-
colorSteps.push(colorSteps[colorSteps.length - 1].slice());
34-
}
27+
updateColor(position, colorSteps, arrayNew.length - 1, [0], []);
3528
}
3629

30+
// concatenate remaining values
31+
updateColor(position, colorSteps, arrayNew.length, arrayA, arrayB);
32+
if (arrayA.length !== 0) arrayNew = arrayNew.concat(arrayA);
33+
if (arrayB.length !== 0) arrayNew = arrayNew.concat(arrayB);
34+
insertStep(arrayNew, position, arraySteps);
35+
36+
return arrayNew;
37+
}
38+
39+
function updateColor(position, colorSteps, start, arrayA, arrayB) {
3740
if (position === 0) {
41+
// if sorted from the front, mark changed elements to be green
3842
let colorKey = colorSteps[colorSteps.length - 1].slice();
39-
colorKey.fill(true, position + arrayNew.length, position + arrayNew.length + arrayA.length + arrayB.length);
43+
colorKey.fill(true, start, start + arrayA.length + arrayB.length);
4044
colorSteps.push(colorKey);
4145
} else {
46+
// or duplicate previous step
4247
colorSteps.push(colorSteps[colorSteps.length - 1].slice());
4348
}
44-
45-
if (arrayA.length !== 0) arrayNew = arrayNew.concat(arrayA);
46-
if (arrayB.length !== 0) arrayNew = arrayNew.concat(arrayB);
47-
48-
insertStep(arrayNew, position, arraySteps);
49-
50-
return arrayNew;
5149
}
5250

5351
export default mergeSort;

0 commit comments

Comments
 (0)