From 26811e36ddea28fa2dc2bc8804e05bf1e0ac64db Mon Sep 17 00:00:00 2001 From: Daniel Date: Sun, 19 Dec 2021 11:11:17 -0700 Subject: [PATCH] Optimized PairingHeap.Extract, shortening code, improving execution time, and reducing allocation. --- pairing-heap-csharp/PairingHeap.cs | 29 ++++++++++------------------- 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/pairing-heap-csharp/PairingHeap.cs b/pairing-heap-csharp/PairingHeap.cs index bb9da82..0c519da 100644 --- a/pairing-heap-csharp/PairingHeap.cs +++ b/pairing-heap-csharp/PairingHeap.cs @@ -107,39 +107,30 @@ private PairingNode Link(PairingNode node1, PairingNode node2) private PairingNode Extract(PairingNode node) { - var children = new List>(); + if (node.Child is null) + return null; + + PairingNode result = null; var n = node.Child; while (!object.ReferenceEquals(n, null)) { + if (n.Sibling is null) + return Link(result, n); + var pair = n.Sibling; n.Parent = null; n.Sibling = null; - if (object.ReferenceEquals(pair, null)) - { - children.Add(n); - break; - } var next = pair.Sibling; pair.Parent = null; pair.Sibling = null; - children.Add(Link(n, pair)); - n = next; - } + result = Link(result, Link(n, pair)); - if (children.Count == 0) - { - return null; - } - - var root = children[0]; - for (var i = 1; i < children.Count; ++i) - { - root = Link(root, children[i]); + n = next; } - return root; + return result; } public int Count