From 51404b019013ccebca201d7cf30e6ae5a7bbb416 Mon Sep 17 00:00:00 2001 From: Daniel Rodriguez Date: Wed, 8 Apr 2020 17:51:53 +0200 Subject: [PATCH 1/2] Optimize vertex removal from UndirectedSparseGraph --- DataStructures/Graphs/UndirectedSparseGraph.cs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/DataStructures/Graphs/UndirectedSparseGraph.cs b/DataStructures/Graphs/UndirectedSparseGraph.cs index 3593c0ec..8f4e5d4e 100644 --- a/DataStructures/Graphs/UndirectedSparseGraph.cs +++ b/DataStructures/Graphs/UndirectedSparseGraph.cs @@ -236,19 +236,16 @@ public virtual bool RemoveVertex(T vertex) if (!_adjacencyList.ContainsKey(vertex)) return false; - _adjacencyList.Remove(vertex); - - foreach (var adjacent in _adjacencyList) + var neighbors = Neighbours(vertex); + foreach (var neighbor in neighbors) { - if (adjacent.Value.Contains(vertex)) - { - adjacent.Value.Remove(vertex); - - // Decrement the edges count. - --_edgesCount; - } + _adjacencyList[neighbor].Remove(vertex); } + _edgesCount -= neighbors.Count; + + _adjacencyList.Remove(vertex); + return true; } From f46d33f37ea99b4a92d0890f903e76e762f78603 Mon Sep 17 00:00:00 2001 From: Daniel Rodriguez Date: Wed, 8 Apr 2020 17:58:41 +0200 Subject: [PATCH 2/2] Avoid try-catch on DLinkedList Contains for performance --- DataStructures/Lists/DLinkedList.cs | 36 ++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/DataStructures/Lists/DLinkedList.cs b/DataStructures/Lists/DLinkedList.cs index e2fa6a1a..8dfe83f1 100644 --- a/DataStructures/Lists/DLinkedList.cs +++ b/DataStructures/Lists/DLinkedList.cs @@ -557,14 +557,7 @@ public virtual void Clear() /// True if found; false otherwise. public virtual bool Contains(T dataItem) { - try - { - return Find(dataItem).IsEqualTo(dataItem); - } - catch (Exception) - { - return false; - } + return TryFind(dataItem, out var found) && found.IsEqualTo(dataItem); } /// @@ -589,6 +582,33 @@ public virtual T Find(T dataItem) throw new Exception("Item was not found."); } + /// + /// Tries to find the specified item in the list. + /// + /// Value to find. + /// Value if found, default otherwise. + /// value. + public virtual bool TryFind(T dataItem, out T found) + { + found = default; + + if (IsEmpty()) return false; + + var currentNode = _firstNode; + while (currentNode != null) + { + if (currentNode.Data.IsEqualTo(dataItem)) + { + found = dataItem; + return true; + } + + currentNode = currentNode.Next; + } + + return false; + } + /// /// Tries to find a match for the predicate. Returns true if found; otherwise false. ///