Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit83978e9

Browse files
refactored merge sort to use array pointers instead of .shift() (trekhleb#581)
1 parented52a80 commit83978e9

File tree

1 file changed

+30
-24
lines changed

1 file changed

+30
-24
lines changed
Lines changed: 30 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
importSortfrom'../Sort';
1+
importSortfrom"../Sort";
22

33
exportdefaultclassMergeSortextendsSort{
44
sort(originalArray){
@@ -24,36 +24,42 @@ export default class MergeSort extends Sort {
2424
}
2525

2626
mergeSortedArrays(leftArray,rightArray){
27-
letsortedArray=[];
27+
constsortedArray=[];
2828

29-
//In case if arrays are not of size 1.
30-
while(leftArray.length&&rightArray.length){
31-
letminimumElement=null;
29+
//Use array pointers to exclude old elements after they have been added to the sorted array
30+
letleftIndex=0;
31+
letrightIndex=0;
3232

33-
// Find minimum element of two arrays.
34-
if(this.comparator.lessThanOrEqual(leftArray[0],rightArray[0])){
35-
minimumElement=leftArray.shift();
36-
}else{
37-
minimumElement=rightArray.shift();
38-
}
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]);
3942

40-
//Call visiting callback.
41-
this.callbacks.visitingCallback(minimumElement);
43+
//Increment index pointer to the right
44+
leftIndex+=1;
4245

43-
// Push the minimum element of two arrays to the sorted array.
44-
sortedArray.push(minimumElement);
45-
}
46+
// Call visiting callback.
47+
this.callbacks.visitingCallback(leftArray[leftIndex]);
48+
}else{
49+
sortedArray.push(rightArray[rightIndex]);
4650

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-
}
51+
// Increment index pointer to the right
52+
rightIndex+=1;
5253

53-
if(rightArray.length){
54-
sortedArray=sortedArray.concat(rightArray);
54+
// Call visiting callback.
55+
this.callbacks.visitingCallback(rightArray[rightIndex]);
56+
}
5557
}
5658

57-
returnsortedArray;
59+
// There will be one element remaining from either the left OR the right
60+
// Concatenate the remaining element into the sorted array
61+
returnsortedArray
62+
.concat(leftArray.slice(leftIndex))
63+
.concat(rightArray.slice(rightIndex));
5864
}
5965
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp