Skip to content

Commit 009090e

Browse files
refactor(core): Optimize and clarify _pdqSiftDown in heapsort
This commit refactors the _pdqSiftDown helper function, which is used as part of the heapsort fallback mechanism within the quickSort implementation. The changes improve both performance and readability: 1- Key Caching: The key of the current largest element is now cached in a local variable (largestKey). This avoids multiple redundant calls to the keyOf function within the loop, reducing overhead. 2- Clearer Logic: The comparison logic has been restructured. Instead of potentially re-evaluating keyOf(elements[start + largest]) after the first comparison, the cached key is used, and the flow for comparing the root with its left and right children is now more explicit and easier to follow. 3- Early Exit: An early break is introduced for leaf nodes (when left >= n), which slightly simplifies the control flow. These changes do not alter the algorithm's behavior but make the implementation more efficient and maintainable.
1 parent 307ec48 commit 009090e

File tree

1 file changed

+22
-15
lines changed

1 file changed

+22
-15
lines changed

pkgs/collection/lib/src/algorithms.dart

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -578,24 +578,31 @@ void _pdqSiftDown<E, K>(List<E> elements, K Function(E) keyOf,
578578
var root = i;
579579
while (true) {
580580
final left = 2 * root + 1;
581-
final right = 2 * root + 2;
582-
var largest = root;
581+
if (left >= n) break; // Root is a leaf.
583582

584-
if (left < n &&
585-
compare(keyOf(elements[start + largest]),
586-
keyOf(elements[start + left])) <
587-
0) {
588-
largest = left;
589-
}
590-
if (right < n &&
591-
compare(keyOf(elements[start + largest]),
592-
keyOf(elements[start + right])) <
593-
0) {
594-
largest = right;
583+
var largest = root;
584+
var largestKey = keyOf(elements[start + largest]);
585+
586+
// Compare with left child.
587+
var child = left;
588+
var childKey = keyOf(elements[start + child]);
589+
if (compare(largestKey, childKey) < 0) {
590+
largest = child;
591+
largestKey = childKey;
595592
}
596-
if (largest == root) {
597-
break;
593+
594+
// Compare with right child if it exists.
595+
child = left + 1;
596+
if (child < n) {
597+
childKey = keyOf(elements[start + child]);
598+
if (compare(largestKey, childKey) < 0) {
599+
largest = child;
600+
largestKey = childKey;
601+
}
598602
}
603+
604+
if (largest == root) break;
605+
599606
_pdqSwap(elements, start + root, start + largest);
600607
root = largest;
601608
}

0 commit comments

Comments
 (0)