public Heap(Vertix[] vertices) { heap = new HeapNode[vertices.Length - 1]; for (int i = 1; i < vertices.Length; i++) { heap[i - 1] = new HeapNode(vertices[i]); heap[i - 1].MyIdx = i - 1; heap[i - 1].ParentIdx = (i / 2) - 1; if ((i * 2) - 1 < heap.Length) { heap[i - 1].LeftChildIdx = (i * 2) - 1; } else { heap[i - 1].LeftChildIdx = -1; } if ((i * 2) < heap.Length) { heap[i - 1].RightChildIdx = (i * 2); } else { heap[i - 1].RightChildIdx = -1; } } nodesInHeap = heap.Length; }
static Dictionary <int, int> GetShortestPaths2(Vertix[] vertices) { var watch2 = System.Diagnostics.Stopwatch.StartNew(); Heap heap = new Heap(vertices); Dictionary <int, int> results = new Dictionary <int, int>(); bool doWhile = true; while (doWhile) { HeapNode temp = heap.Deheapify(); if (temp != null) { results.Add(temp.MyVertix.Number, temp.ShortestDistance); } else { doWhile = false; } } watch2.Stop(); var elapsedMs2 = watch2.ElapsedMilliseconds; return(results); }
void RearrengeWithParent(HeapNode node) { if (node.ParentIdx != -1 && heap[node.ParentIdx] != null) { int parent = node.ParentIdx; if (RearrengeWithChild(heap[parent])) { RearrengeWithParent(node); } } }
bool RearrengeWithChild(HeapNode node) { bool swapped = false; if (node.LeftChildIdx != -1 && heap[node.LeftChildIdx] != null && node.ShortestDistance > heap[node.LeftChildIdx].ShortestDistance) { swapped = true; SwapWithParent(node.MyIdx, node.LeftChildIdx); RearrengeWithChild(heap[node.MyIdx]); } else if (node.RightChildIdx != -1 && heap[node.RightChildIdx] != null && node.ShortestDistance > heap[node.RightChildIdx].ShortestDistance) { swapped = true; SwapWithParent(node.MyIdx, node.RightChildIdx); RearrengeWithChild(heap[node.MyIdx]); } return(swapped); }