Skip to content

Commit 9b315ed

Browse files
committed
optimization: avoid unnecessary merge sort
1 parent 830cffb commit 9b315ed

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

code.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,19 @@
403403
// From: https://en.wikipedia.org/wiki/Merge_sort
404404
function topDownSplitMerge(B, iBegin, iEnd, A) {
405405
if (iEnd - iBegin <= 6) return;
406+
407+
// Optimization: Don't do merge sort if it's already sorted
408+
let isAlreadySorted = true;
409+
for (let i = iBegin + 3, j = i + 6; j < iEnd; i = j, j += 6) {
410+
// Compare mappings first by original line (index 3) and then by original column (index 4)
411+
if (A[i] < A[j] || (A[i] === A[j] && A[i + 1] <= A[j + 1])) continue;
412+
isAlreadySorted = false;
413+
break;
414+
}
415+
if (isAlreadySorted) {
416+
return;
417+
}
418+
406419
const iMiddle = ((iEnd / 6 + iBegin / 6) >> 1) * 6;
407420
topDownSplitMerge(A, iBegin, iMiddle, B);
408421
topDownSplitMerge(A, iMiddle, iEnd, B);

0 commit comments

Comments
 (0)