Beispiel #1
0
        public static List <T> Sort(T[] input)
        {
            var list = new List <T>();
            var heap = new MinHeap <T>(input.Length, input);

            for (int i = input.Length - 1; i >= 0; i--)
            {
                list.Add(heap.array[0]);
                var tmp = heap.array[0];
                heap.array[0] = heap.array[i];
                heap.heapSize--;
                heap.Heapify(0);
            }
            return(list);
        }
Beispiel #2
0
        public void MinimumSpanningTreePrim(VertexMST <T> root)
        {
            foreach (var vertex in vertices.OfType <VertexMST <T> >())
            {
                vertex.Key         = int.MaxValue;
                vertex.Predecessor = null;
            }
            root.Key = 0;
            var heap = new MinHeap <VertexMST <T> >(vertices.Count, vertices.OfType <VertexMST <T> >().ToArray());

            while (!heap.IsEmpty)
            {
                //had to call heapify before extract min since it's not a min heap anymore due to the change of keys
                //instead of decrease key
                heap.Heapify(0);
                var min = heap.Extract();
                foreach (var edge in edges.Where((e) => e.From.Equals(min) || e.To.Equals(min)))
                {
                    if (edge.To.Equals(min))
                    {
                        if (heap.Contains(edge.From as VertexMST <T>) &&
                            edge.Weight < (edge.From as VertexMST <T>).Key)
                        {
                            edge.From.Predecessor            = min;
                            (edge.From as VertexMST <T>).Key = edge.Weight;
                        }
                    }
                    else
                    {
                        if (heap.Contains(edge.To as VertexMST <T>) &&
                            edge.Weight < (edge.To as VertexMST <T>).Key)
                        {
                            edge.To.Predecessor            = min;
                            (edge.To as VertexMST <T>).Key = edge.Weight;
                        }
                    }
                }
            }
        }