Click here to Skip to main content
15,891,734 members
Articles / Multimedia / GDI+

Kruskal Algorithm

Rate me:
Please Sign up or sign in to vote.
4.84/5 (47 votes)
5 Jul 2012CPOL2 min read 183.7K   11.6K   70  
Implementation of Kruskal Algorithm in C#
using System;

namespace KruskalAlgorithm
{
    class Vertex
    {
        #region Members
        int nName;
        public int nRank;
        public Vertex vRoot;
        public System.Drawing.Point pPosition;
        #endregion

        #region Properties
        public int Name
        {
            get
            {
                return nName;
            }
        }
        #endregion

        public Vertex(int nName, System.Drawing.Point pPosition)
        {
            this.nName = nName;
            nRank = 0;
            this.vRoot = this;
            this.pPosition = pPosition;
        }

        #region Methods
        internal Vertex GetRoot()
        {
            if (this.vRoot != this)// am I my own parent ? (am i the root ?)
            {
                this.vRoot = this.vRoot.GetRoot();// No? then get my parent
            }
            return this.vRoot;
        }

        internal static void Join(Vertex vRoot1, Vertex vRoot2)
        {

            if (vRoot2.nRank < vRoot1.nRank)//is the rank of Root2 less than that of Root1 ?
            {
                vRoot2.vRoot = vRoot1;//yes! then Root1 is the parent of Root2 (since it has the higher rank)
            }
            else //rank of Root2 is greater than or equal to that of Root1
            {
                vRoot1.vRoot = vRoot2;//make Root2 the parent
                if (vRoot1.nRank == vRoot2.nRank)//both ranks are equal ?
                {
                    vRoot1.nRank++;//increment one of them, we need to reach a single root for the whole tree
                }
            }
        }
        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Egypt Egypt
Enthusiastic programmer/researcher, passionate to learn new technologies, interested in problem solving, data structures, algorithms, AI, machine learning and nlp.

Amateur guitarist/ keyboardist, squash player.

Comments and Discussions