Skip to content

GH-174: Priority Queue (Heap) in C++ #175

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Mar 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,12 @@ A data structure is a data organization, management, and storage format that is
</td>
</tr>
<tr>
<td>Priority Queue (Heap)</td>
<td>
<a href="/concepts/cpp/priority_queue.md"><code>cpp🐀</code></a>
</td>
</tr>
<tr>
<td colspan="2" align="center"><b>Algorithms</b></td>
</tr>
<tr>
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
220 changes: 220 additions & 0 deletions concepts/cpp/labs/priority_queue.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Priority Queue \n",
"\n",
"A priority queue is a container that provides constant time lookup of the largest (by default) element, at the expense of logarithmic insertion and extraction.\n",
"\n",
"Real world examples of priority queues include:\n",
"\n",
"- The task queue in an operating system\n",
"- The call queue in a call center\n",
"- The list of pending requests at a web server, sorted by their priority\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Baisc usage of priority queue\n",
"\n",
"C++ has built-in object [`priority_queue`](https://cplusplus.com/reference/queue/priority_queue/) in `queue` library."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"vscode": {
"languageId": "cpp"
}
},
"outputs": [],
"source": [
"#include <queue>\n",
"#include <vector>\n",
"#include <iostream>\n",
"\n",
"using namespace std;"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"vscode": {
"languageId": "cpp"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n",
"3\n",
"1\n"
]
}
],
"source": [
"priority_queue<int> pq;\n",
"\n",
"pq.push(1);\n",
"pq.push(5);\n",
"pq.push(3);\n",
"\n",
"while (!pq.empty()) {\n",
" cout << pq.top() << endl;\n",
" pq.pop();\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Min priority queue\n",
"\n",
"If you want min priority queue, you can use `greater<int>` as the third argument."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"vscode": {
"languageId": "cpp"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"3\n",
"5\n"
]
}
],
"source": [
"priority_queue<int, vector<int>, greater<int>> pq;\n",
"\n",
"pq.push(1);\n",
"pq.push(5);\n",
"pq.push(3);\n",
"\n",
"while (!pq.empty()) {\n",
" cout << pq.top() << endl;\n",
" pq.pop();\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Priority queue with custom comparator\n",
"\n",
"Custom Comparision with `priority_queue` is a little bit interesting. You can use custom struct as the third argument."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"vscode": {
"languageId": "cpp"
}
},
"outputs": [],
"source": [
"struct Node {\n",
" int val;\n",
" int priority;\n",
"};\n",
"\n",
"struct compare{\n",
" public:\n",
" bool operator()(Node& a,Node& b)\n",
" {\n",
" return a.priority < b.priority;\n",
" }\n",
"};"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"vscode": {
"languageId": "cpp"
}
},
"outputs": [],
"source": [
"priority_queue<Node, vector<Node>, compare> pq;\n",
"pq.push({1, 2});\n",
"pq.push({5, 6});\n",
"pq.push({10, 3});"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"vscode": {
"languageId": "cpp"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5, 6\n",
"10, 3\n",
"1, 2\n"
]
}
],
"source": [
"while(!pq.empty()){\n",
" Node tmp = pq.top();\n",
" cout << tmp.val << \", \" << tmp.priority << endl;\n",
" pq.pop();\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## References\n",
"\n",
"* [Declaring a priority_queue in c++ with a custom comparator](https://stackoverflow.com/questions/16111337/declaring-a-priority-queue-in-c-with-a-custom-comparator)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "C++17",
"language": "C++17",
"name": "xcpp17"
},
"language_info": {
"codemirror_mode": "text/x-c++src",
"file_extension": ".cpp",
"mimetype": "text/x-c++src",
"name": "c++",
"version": "17"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
63 changes: 63 additions & 0 deletions concepts/cpp/priority_queue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Priority Queue

<a href="https://github.com/rain1024/datastructures-algorithms-competitive-programming/blob/main/concepts/cpp/labs/priority_queue.ipynb">
<img src="https://img.shields.io/badge/🧪-notebook-brightgreen">
</a>

A priority queue is an abstract data type that allows the storage of elements with priority. The elements are stored in such a way that the element with the highest priority is always at the front of the queue, and the element with the lowest priority is at the back of the queue.

![](../abstract/data-structures/priority_queue.png)


## 🎨 Priority Queue Design

**Methods**

| | Definition |
|----------------|-------------------------------------------------------------|
| enqueue | Add element to the queue |
| dequeue | remove the element with the highest priority from the queue |


## 💻 Priority Queue Implementation in C++

C++ has built-in object [`priority_queue`](https://cplusplus.com/reference/queue/priority_queue/) in `queue` library.

```cpp
#include <iostream>
#include <queue>

int main(){
priority_queue<int> pq;

pq.push(1);
pq.push(5);
pq.push(3);

while (!pq.empty()) {
cout << pq.top() << endl;
pq.pop();
}

return 0;
}

```

## 📈 Complexity Analysis of Priority Queue


| Operation | Complexity |
|-----------------|---------------------|
| push | $O(log N)$ |
| pop | $O(log N)$ |
| top | $O(1)$ |

## 🔗 Further Reading

* [Priority Queue (data structures)](https://en.wikipedia.org/wiki/Priority_queue), wikipedia
* ▶️ [Priority Queue (1/5) Introduction](https://www.youtube.com/watch?v=wptevk0bshY&ab_channel=WilliamFiset), WilliamFiset, 2017
* ▶️ [Priority Queue (2/5) Min Heaps and Max Heaps](https://www.youtube.com/watch?v=HCEr35qpawQ&ab_channel=WilliamFiset), WilliamFiset, 2017
* ▶️ [Priority Queue (3/5) Inserting Elements](https://www.youtube.com/watch?v=QOJ-CmQiXko&list=PLDV1Zeh2NRsB6SWUrDFW2RmDotAfPbeHu&index=16&ab_channel=WilliamFiset), WilliamFiset, 2017
* ▶️ [Priority Queue (4/5) Removing Elements](https://www.youtube.com/watch?v=eVq8CmoC1x8&list=PLDV1Zeh2NRsB6SWUrDFW2RmDotAfPbeHu&index=17&ab_channel=WilliamFiset), WilliamFiset, 2017
* ▶️ [Priority Queue (5/5) Code](https://www.youtube.com/watch?v=GLIRnUhknP0&list=PLDV1Zeh2NRsB6SWUrDFW2RmDotAfPbeHu&index=18&ab_channel=WilliamFiset), WilliamFiset, 2017
2 changes: 1 addition & 1 deletion concepts/cpp/tree.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ int main()
}
```

## 📈 Complexity Analysis of [Awesome Type]
## 📈 Complexity Analysis of Tree


| Operation | Complexity |
Expand Down