public (int, List <Edge>) SolveKruskal(int[,] graph, int size)
        {
            List <Edge> newGraph = _graphInit.FromMatrixToListEdges(graph, size);

            int[]       treeId = new int[size];
            List <Edge> mst    = new List <Edge>();

            Edge[] newGr = newGraph.ToArray();
            SeqSort.StartQuickSort(newGr);
            newGraph = newGr.ToList();

            int weightOfTree = 0;

            for (int i = 0; i < size; ++i)
            {
                treeId[i] = i;
            }

            foreach (var edge in newGraph)
            {
                int firstNode  = edge.begin;
                int secondNode = edge.end;
                int weight     = edge.weight;

                if (treeId[firstNode] != treeId[secondNode])
                {
                    weightOfTree += weight;
                    mst.Add(new Edge(firstNode, secondNode, weight));

                    int firstSubTree  = treeId[firstNode];
                    int secondSubTree = treeId[secondNode];

                    for (int indexNode = 0; indexNode < size; ++indexNode)
                    {
                        if (treeId[indexNode] == secondSubTree)
                        {
                            treeId[indexNode] = firstSubTree;
                        }
                    }
                }
            }

            return(weightOfTree, mst);
        }
Exemplo n.º 2
0
        private static void QuickSort <T>(T[] items, int left, int right)
            where T : IComparable <T>
        {
            if (right - left < 2)
            {
                return;
            }

            int pivot = SeqSort.Partition(items, left, right);

            if (right - left > 300)
            {
                Task leftTask  = Task.Run(() => QuickSort(items, left, pivot));
                Task rightTask = Task.Run(() => QuickSort(items, pivot + 1, right));

                Task.WaitAll(leftTask, rightTask);
            }
            else
            {
                SeqSort.QuickSort(items, left, pivot);
                SeqSort.QuickSort(items, pivot + 1, right);
            }
        }