I'm trying to implement Kruskal's algortihm in C# and I got such
NullReferenceException: subsets[] was null
Here is my class Graph and Kruskal's algortihm with some needed methods
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace Application
{
public class Graph
{
public List<Vertex> Vertexes = new List<Vertex>();
public List<Edge> Edges = new List<Edge>();
public int VertexCount => Vertexes.Count;
public int EdgesCount => Edges.Count;
public void Add(Vertex vertex)
{
Vertexes.Add(vertex);
}
public void Add(Vertex from, Vertex to, int weight)
{
var edge = new Edge(from, to, weight);
Edges.Add(edge);
}
public void Kruskal(Graph graph)
{
Edge[] edges = Edges.ToArray();
int verticesCount = graph.VertexCount;
Edge[] result = new Edge[verticesCount];
int i = 0;
int e = 0;
Array.Sort(edges, delegate (Edge a, Edge b)
{
return a.Weight.CompareTo(b.Weight);
});
//exception is here
Subset[] subsets = new Subset[verticesCount];
for (int v = 0; v < verticesCount; ++v)
{
subsets[v].Parent = v;
subsets[v].Rank = 0;
}
while (e < verticesCount - 1)
{
Edge nextEdge = edges[i++];
int x = Find(subsets, nextEdge.From.Number);
int y = Find(subsets, nextEdge.To.Number);
if (x != y)
{
result[e++] = nextEdge;
Union(subsets, x, y);
}
}
Print(result, e);
}
private int Find(Subset[] subsets, int i)
{
if (subsets[i].Parent != i)
subsets[i].Parent = Find(subsets, subsets[i].Parent);
return subsets[i].Parent;
}
private void Union(Subset[] subsets, int x, int y)
{
int xroot = Find(subsets, x);
int yroot = Find(subsets, y);
if (subsets[xroot].Rank < subsets[yroot].Rank)
subsets[xroot].Parent = yroot;
else if (subsets[xroot].Rank > subsets[yroot].Rank)
subsets[yroot].Parent = xroot;
else
{
subsets[yroot].Parent = xroot;
++subsets[xroot].Rank;
}
}
private static void Print(Edge[] result, int e)
{
for (int i = 0; i < e; ++i)
Console.WriteLine("{0} -- {1} == {2}", result[i].From.Number, result[i].To.Number, result[i].Weight);
}
}
}
Here is my Subset class
using System;
using System.Collections.Generic;
using System.Text;
namespace Application
{
class Subset
{
public int Parent;
public int Rank;
}
}
I can't actually understand, why my array is empty and how to fix this issue. If you know something, please, write about it