Skip to content

Commit 32c6411

Browse files
committed
feat: add PriorityQueueBasedOnNaturalOrdering demonstrating Java PriorityQueue behavior
Implemented PriorityQueueBasedOnNaturalOrdering.java to showcase natural ordering (min-heap) behavior of PriorityQueue. Demonstrates insertion, polling, and iteration order, explaining that elements are ordered by natural order (lowest first for numbers) and can be customized using comparators. Includes notes on internal heap structure and O(log n) insertion complexity. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 143f0d6 commit 32c6411

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

Section 25 Collections Frameworks/Queue Interface/Priority Queue/src/PriorityQueueBasedOnNaturalOrdering.java

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,15 @@
22

33
public class PriorityQueueBasedOnNaturalOrdering {
44
public static void main(String[] args) {
5-
// part of the Queue interface
6-
// orders elements based on their natural ordering (for primitives lowest first)
7-
// custom comparator for customised ordering
8-
// does not allow null elements
5+
/*
6+
part of the Queue interface
7+
orders elements based on their natural ordering (for primitives lowest first)
8+
custom comparator for customized ordering
9+
does not allow null elements
10+
*/
911
PriorityQueue<Integer> pq = new PriorityQueue<>();
1012

13+
// We can use if we don't need natural ordering of elements, Custom comparator.
1114
//PriorityQueue<Integer> pq = new PriorityQueue<>((x,y)->x-y);
1215

1316
pq.add(15);
@@ -16,14 +19,17 @@ public static void main(String[] args) {
1619
pq.add(5);
1720
System.out.println(pq); // not sorted
1821

19-
//Queue Retrieves and removes the head of this queue, or returns null if this queue is empty.
22+
// System.out.println(pq.); // Check methods inside Queue.
23+
24+
//Queue Retrieves and removes the head of this queue or returns null if this queue is empty.
2025
while (!pq.isEmpty()) {
2126
System.out.println(pq.poll());
2227
}
23-
/* internal working:
2428

29+
/*
30+
internal working:
2531
PriorityQueue is implemented as a min-heap by default (for natural ordering).
2632
Time complexity of min-heap inserting an element is O(Log n).
2733
*/
2834
}
29-
}
35+
}

0 commit comments

Comments
 (0)