Last active
January 1, 2024 14:20
-
-
Save Krasipeace/a18eadff9e586bdba11a131ab73943aa to your computer and use it in GitHub Desktop.
Priority Queue Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PriorityQueue<T> | |
{ | |
private List<T> heap; | |
private IComparer<T> comparer; | |
public PriorityQueue() | |
{ | |
heap = new List<T>(); | |
comparer = Comparer<T>.Default; | |
} | |
public T Peek() => heap[0]; | |
public int Count => heap.Count; | |
public void Clear() => heap.Clear(); | |
public bool Contains(T item) => heap.Contains(item); | |
public bool IsEmpty() => heap.Count == 0; | |
public T[] ToArray () => heap.ToArray(); | |
public void Enqueue(T item) | |
{ | |
heap.Add(item); | |
int last = heap.Count - 1; | |
while (last > 0) | |
{ | |
int parent = (last - 1) / 2; | |
if (comparer.Compare(heap[parent], heap[last]) <= 0) | |
{ | |
break; | |
} | |
(heap[last], heap[parent]) = (heap[parent], heap[last]); | |
last = parent; | |
} | |
} | |
public T Dequeue() | |
{ | |
int lastIndex = heap.Count - 1; | |
T frontItem = heap[0]; | |
heap[0] = heap[lastIndex]; | |
heap.RemoveAt(lastIndex); | |
lastIndex--; | |
int parent = 0; | |
while (true) | |
{ | |
int leftChild = parent * 2 + 1; | |
int rightChild = parent * 2 + 2; | |
if (leftChild > lastIndex) | |
{ | |
break; | |
} | |
int minChild = leftChild; | |
if (rightChild <= lastIndex && comparer.Compare(heap[leftChild], heap[rightChild]) > 0) | |
{ | |
minChild = rightChild; | |
} | |
if (comparer.Compare(heap[parent], heap[minChild]) <= 0) | |
{ | |
break; | |
} | |
(heap[minChild], heap[parent]) = (heap[parent], heap[minChild]); | |
parent = minChild; | |
} | |
return frontItem; | |
} | |
public void RemoveItem(T item) | |
{ | |
int index = heap.IndexOf(item); | |
int lastIndex = heap.Count - 1; | |
heap[index] = heap[lastIndex]; | |
heap.RemoveAt(lastIndex); | |
lastIndex--; | |
int parent = index; | |
while (true) | |
{ | |
int leftChild = parent * 2 + 1; | |
int rightChild = parent * 2 + 2; | |
if (leftChild > lastIndex) | |
{ | |
break; | |
} | |
int minChild = leftChild; | |
if (rightChild <= lastIndex && comparer.Compare(heap[leftChild], heap[rightChild]) > 0) | |
{ | |
minChild = rightChild; | |
} | |
if (comparer.Compare(heap[parent], heap[minChild]) <= 0) | |
{ | |
break; | |
} | |
(heap[minChild], heap[parent]) = (heap[parent], heap[minChild]); | |
parent = minChild; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment