From 6be6a2f238fb9246ad79e13c02434c26e7dbdecf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gy=C5=91ri=20Mih=C3=A1ly?= Date: Fri, 24 Nov 2017 16:13:50 +0100 Subject: [PATCH] Remove doubling of size Added check so already connected values does not double the size. Currently, if the root of the two numbers we want to add to the union are already connected, the size gets double. Checking for isConnected is also an option, but this is a faster approach. --- .../WeightedQuickUnionWithPathCompression.cs | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/cs-algorithms/UnionFind/WeightedQuickUnionWithPathCompression.cs b/cs-algorithms/UnionFind/WeightedQuickUnionWithPathCompression.cs index 8eb0403..26a41be 100644 --- a/cs-algorithms/UnionFind/WeightedQuickUnionWithPathCompression.cs +++ b/cs-algorithms/UnionFind/WeightedQuickUnionWithPathCompression.cs @@ -40,16 +40,19 @@ public void Union(int p, int q) { int i = GetRoot(p); int j = GetRoot(q); - if (mSize[i] < mSize[j]) + if (i!=j) { - mParent[i] = j; - mSize[j] += mSize[i]; - } - else - { - mParent[j] = i; - mSize[i] += mSize[j]; - } + if (mSize[i] < mSize[j]) + { + mParent[i] = j; + mSize[j] += mSize[i]; + } + else + { + mParent[j] = i; + mSize[i] += mSize[j]; + } + } } public bool IsConnected(int i, int j)