@@ -24,36 +24,37 @@ export default class MergeSort extends Sort {
24
24
}
25
25
26
26
mergeSortedArrays ( leftArray , rightArray ) {
27
- let sortedArray = [ ] ;
27
+ const sortedArray = [ ] ;
28
28
29
- // In case if arrays are not of size 1 .
30
- while ( leftArray . length && rightArray . length ) {
31
- let minimumElement = null ;
29
+ // Use array pointers to exclude old elements after they have been added to the sorted array .
30
+ let leftIndex = 0 ;
31
+ let rightIndex = 0 ;
32
32
33
- // Find minimum element of two arrays.
34
- if ( this . comparator . lessThanOrEqual ( leftArray [ 0 ] , rightArray [ 0 ] ) ) {
35
- minimumElement = leftArray . shift ( ) ;
33
+ while ( leftIndex < leftArray . length && rightIndex < rightArray . length ) {
34
+ let minElement = null ;
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 ] ;
39
+ // Increment index pointer to the right
40
+ leftIndex += 1 ;
36
41
} else {
37
- minimumElement = rightArray . shift ( ) ;
42
+ minElement = rightArray [ rightIndex ] ;
43
+ // Increment index pointer to the right
44
+ rightIndex += 1 ;
38
45
}
39
46
40
- // Call visiting callback.
41
- this . callbacks . visitingCallback ( minimumElement ) ;
42
-
43
- // Push the minimum element of two arrays to the sorted array.
44
- sortedArray . push ( minimumElement ) ;
45
- }
47
+ // Add the minimum element to the sorted array.
48
+ sortedArray . push ( minElement ) ;
46
49
47
- // If one of two array still have elements we need to just concatenate
48
- // this element to the sorted array since it is already sorted.
49
- if ( leftArray . length ) {
50
- sortedArray = sortedArray . concat ( leftArray ) ;
51
- }
52
-
53
- if ( rightArray . length ) {
54
- sortedArray = sortedArray . concat ( rightArray ) ;
50
+ // Call visiting callback.
51
+ this . callbacks . visitingCallback ( minElement ) ;
55
52
}
56
53
57
- return sortedArray ;
54
+ // There will be elements remaining from either the left OR the right
55
+ // Concatenate the remaining elements into the sorted array
56
+ return sortedArray
57
+ . concat ( leftArray . slice ( leftIndex ) )
58
+ . concat ( rightArray . slice ( rightIndex ) ) ;
58
59
}
59
60
}
0 commit comments