|
1 |
| -import Sort from "../Sort"; |
| 1 | +import Sort from '../Sort'; |
2 | 2 |
|
3 | 3 | export default class MergeSort extends Sort {
|
4 | 4 | sort(originalArray) {
|
@@ -26,38 +26,33 @@ export default class MergeSort extends Sort {
|
26 | 26 | mergeSortedArrays(leftArray, rightArray) {
|
27 | 27 | const sortedArray = [];
|
28 | 28 |
|
29 |
| - // Use array pointers to exclude old elements after they have been added to the sorted array |
| 29 | + // Use array pointers to exclude old elements after they have been added to the sorted array. |
30 | 30 | let leftIndex = 0;
|
31 | 31 | let rightIndex = 0;
|
32 | 32 |
|
33 | 33 | while (leftIndex < leftArray.length && rightIndex < rightArray.length) {
|
34 |
| - // Find the minimum element between the left and right array |
35 |
| - if ( |
36 |
| - this.comparator.lessThanOrEqual( |
37 |
| - leftArray[leftIndex], |
38 |
| - rightArray[rightIndex] |
39 |
| - ) |
40 |
| - ) { |
41 |
| - sortedArray.push(leftArray[leftIndex]); |
| 34 | + let minElement = null; |
42 | 35 |
|
| 36 | + // Find the minimum element between the left and right array. |
| 37 | + if (this.comparator.lessThanOrEqual(leftArray[leftIndex], rightArray[rightIndex])) { |
| 38 | + minElement = leftArray[leftIndex]; |
43 | 39 | // Increment index pointer to the right
|
44 | 40 | leftIndex += 1;
|
45 |
| - |
46 |
| - // Call visiting callback. |
47 |
| - this.callbacks.visitingCallback(leftArray[leftIndex]); |
48 | 41 | } else {
|
49 |
| - sortedArray.push(rightArray[rightIndex]); |
50 |
| - |
| 42 | + minElement = rightArray[rightIndex]; |
51 | 43 | // Increment index pointer to the right
|
52 | 44 | rightIndex += 1;
|
53 |
| - |
54 |
| - // Call visiting callback. |
55 |
| - this.callbacks.visitingCallback(rightArray[rightIndex]); |
56 | 45 | }
|
| 46 | + |
| 47 | + // Add the minimum element to the sorted array. |
| 48 | + sortedArray.push(minElement); |
| 49 | + |
| 50 | + // Call visiting callback. |
| 51 | + this.callbacks.visitingCallback(minElement); |
57 | 52 | }
|
58 | 53 |
|
59 |
| - // There will be one element remaining from either the left OR the right |
60 |
| - // Concatenate the remaining element into the sorted array |
| 54 | + // There will be elements remaining from either the left OR the right |
| 55 | + // Concatenate the remaining elements into the sorted array |
61 | 56 | return sortedArray
|
62 | 57 | .concat(leftArray.slice(leftIndex))
|
63 | 58 | .concat(rightArray.slice(rightIndex));
|
|
0 commit comments