public PQKey Enqueue(T item, double priority) { PQWrapper <T> newItem = new PQWrapper <T>(); newItem.key = new PQKey(); newItem.data = item; newItem.priority = priority; list.Add(newItem); int ci = list.Count - 1; // child index; start at end newItem.key.loc = ci; while (ci > 0) { int pi = (ci - 1) / 2; // parent index if (list[ci].CompareTo(list[pi]) >= 0) { break; // child item is larger than (or equal) parent so we're done } PQWrapper <T> tmp = list[ci]; list[ci] = list[pi]; list[pi] = tmp; list[ci].key.loc = ci; list[pi].key.loc = pi; ci = pi; } return(newItem.key); }
public void ChangePriority(PQKey key, double newP) { double oldP = list[key.loc].priority; list[key.loc].priority = newP; if (oldP > list[key.loc].priority) { int ci = key.loc; while (ci > 0) { int pi = (ci - 1) / 2; // parent index if (list[ci].CompareTo(list[pi]) >= 0) { break; // child item is larger than (or equal) parent so we're done } PQWrapper <T> tmp = list[ci]; list[ci] = list[pi]; list[pi] = tmp; list[ci].key.loc = ci; list[pi].key.loc = pi; ci = pi; } } else { int pi = key.loc; // parent index. start at front of pq int li = list.Count - 1; while (true) { int ci = pi * 2 + 1; // left child index of parent if (ci > li) { break; // no children so done } int rc = ci + 1; // right child if (rc <= li && list[rc].CompareTo(list[ci]) < 0) // if there is a rc (ci + 1), and it is smaller than left child, use the rc instead { ci = rc; } if (list[pi].CompareTo(list[ci]) <= 0) { break; // parent is smaller than (or equal to) smallest child so done } PQWrapper <T> tmp = list[pi]; list[pi] = list[ci]; list[ci] = tmp; // swap parent and child //Adjust key vals list[ci].key.loc = ci; list[pi].key.loc = pi; pi = ci; } } }
public int CompareTo(PQWrapper <T> rhs) { if (this.priority < rhs.priority) { return(-1); } else if (this.priority > rhs.priority) { return(1); } else { return(0); } }
public T Dequeue() { // assumes pq is not empty; up to calling code int li = list.Count - 1; // last index (before removal) T frontItem = list[0].data; // fetch the front list[0] = list[li]; list.RemoveAt(li); --li; // last index (after removal) //Adjust key vals for (int i = 0; i < list.Count; ++i) { list[i].key.loc = i; } int pi = 0; // parent index. start at front of pq while (true) { int ci = pi * 2 + 1; // left child index of parent if (ci > li) { break; // no children so done } int rc = ci + 1; // right child if (rc <= li && list[rc].CompareTo(list[ci]) < 0) // if there is a rc (ci + 1), and it is smaller than left child, use the rc instead { ci = rc; } if (list[pi].CompareTo(list[ci]) <= 0) { break; // parent is smaller than (or equal to) smallest child so done } PQWrapper <T> tmp = list[pi]; list[pi] = list[ci]; list[ci] = tmp; // swap parent and child //Adjust key vals list[ci].key.loc = ci; list[pi].key.loc = pi; pi = ci; } return(frontItem); }