Kruskal Algorithm

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nicromonicon
    New Member
    • Aug 2007
    • 2

    #1

    Kruskal Algorithm

    hey guys,im doing Kruskal algorithm in C#..works fine...but it takes so long on large input?
    i tried using textreader instead of streamreader..s till nothin

    any way to make it faster?



    ///////there is a class Edge that implements IComparable

    static public SortedList union;/*Taken Vertices*/
    static void Main(string[] args)
    {

    const string filename = @"c:\text_.txt" ;
    Console.Title = "Kruskal Algorithm";
    ArrayList graph; /*Initial Graph*/
    object vertex1, vertex2;
    int cost;
    int total_cost = 0;
    #region Read File..Fill Graph
    StreamReader sr = new StreamReader(fi lename);
    string line = sr.ReadLine();
    string[] splitted = new string[2];
    char[] splitter = { ' ' };
    splitted = line.Split(spli tter);
    int num_vertices = int.Parse(split ted[0]);
    int num_edges = int.Parse(split ted[1]);
    graph = new ArrayList(num_e dges);
    union = new SortedList(num_ vertices);

    string fileContent;
    string[] firstLineParsed = line.Split(new char[] { ' ' });
    char[] chars = new char[] { '\n', ' ' };
    fileContent = sr.ReadToEnd();
    string[] s = fileContent.Spl it(chars);
    for (int i = 0; i < num_edges * 3; i += 3)
    {
    vertex1 = s[i];
    vertex2 = s[i+1];
    cost = int.Parse(s[i+2]);
    Edge e = new Edge(vertex1, vertex2, cost);
    graph.Add(e);
    if (!union.Contain sKey(vertex1))
    {
    union.Add(verte x1, vertex1);
    }
    if (!union.Contain sKey(vertex2))
    {
    union.Add(verte x2, vertex2);
    }
    }
    #endregion
    graph.Sort();


    foreach (Edge e in graph)
    {
    if (find(ref e.vertex_1) != find(ref e.vertex_2))
    {
    total_cost += e.cost;
    }
    }
    Console.WriteLi ne(total_cost);
    }

    private static void Join(ref object x, ref object y)
    {
    object xroot, yroot;
    xroot = find(ref x);
    yroot = find(ref y);
    union[xroot] = yroot;
    }

    private static object find(ref object x)
    {
    if (union[x] == x)
    {
    return x;
    }
    else
    {
    object z=union[x];
    return find(ref z);
    }
    }
Working...