Skip to content

Commit 0bc5115

Browse files
authored
Merge pull request #488 from sneekr-a/patch-1
Create priorityqueue_sort.cpp
2 parents 2ed37d8 + 1596650 commit 0bc5115

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <queue> // for priority_queue on line 7
2+
#include <vector> // for vector on line 5
3+
4+
/* Problem
5+
Given a reference to a vector of values, sort the vector using a pqSort.
6+
*/
7+
8+
template <typename T>
9+
void pqSort(std::vector<T>& v)
10+
{
11+
12+
//Step 1) Define a priority queue such that the ordering uses std::greater
13+
std::priority_queue<T, std::vector<T>, std::greater<T>> pq;
14+
15+
//Step 2) Push all values in the vector onto the priority queue
16+
while(!v.empty())
17+
{
18+
pq.push(v.back());
19+
v.pop_back();
20+
}
21+
22+
//Step 3) Pop all vlaues in the priority queue onto the vector
23+
// - Because the priority queue uses the std::greater ordering function
24+
// - to decide where to insert the value in the tree to maintain increasing
25+
// - order, the least value is stored at the top always.
26+
while(!pq.empty())
27+
{
28+
v.emplace_back(pq.top());
29+
pq.pop();
30+
}
31+
32+
}
33+
34+
/* Notes
35+
- pqSort is a relatively efficient and rarely mentioned, since it moreso demonstrates the quality of priority queues to sort at insertion.
36+
- > and also because faster sorting algorithms exist.
37+
- If studying DS&A, this is a good example of priority queues primary functionality.
38+
- You can write your own comparison function to use on your own datatypes, etc, and implement them painlessly.
39+
- > for more info on how to do that, check out std::greater
40+
*/

0 commit comments

Comments
 (0)