Max heap เป็นไบนารีทรีที่สมบูรณ์ โดยที่ค่าของรูทโหนดในทุกขั้นตอนมากกว่าหรือเท่ากับค่าที่โหนดย่อย
ด้านล่างนี้คือการนำ Max Heap ไปใช้งานโดยใช้ฟังก์ชันไลบรารี
ตัวอย่าง
import java.util.*;
public class Demo{
public static void main(String args[]){
PriorityQueue<Integer> my_p_queue = new PriorityQueue<Integer>(Collections.reverseOrder());
my_p_queue.add(43);
my_p_queue.add(56);
my_p_queue.add(99);
System.out.println("The elements in the priority queue are : ");
Iterator my_iter = my_p_queue.iterator();
while (my_iter.hasNext())
System.out.println(my_iter.next());
my_p_queue.poll();
System.out.println("After removing an element using the poll function, the queue elements are :");
Iterator<Integer> my_iter_2 = my_p_queue.iterator();
while (my_iter_2.hasNext())
System.out.println(my_iter_2.next());
Object[] my_arr = my_p_queue.toArray();
System.out.println("The array representation of max heap : ");
for (int i = 0; i < my_arr.length; i++)
System.out.println("Value: " + my_arr[i].toString());
}
} ผลลัพธ์
The elements in the priority queue are : 99 43 56 After removing an element using the poll function, the queue elements are : 56 43 The array representation of max heap : Value: 56 Value: 43
คลาสชื่อ Demo มีฟังก์ชันหลัก ภายในฟังก์ชันหลัก มีการกำหนดอินสแตนซ์ของคิวลำดับความสำคัญ และเพิ่มองค์ประกอบเข้าไปโดยใช้ฟังก์ชัน 'เพิ่ม' ตัววนซ้ำถูกกำหนดและมัน
ใช้เพื่อวนซ้ำองค์ประกอบในคิวลำดับความสำคัญ ฟังก์ชัน 'โพล' ใช้เพื่อลบองค์ประกอบออกจากรายการ ถัดไป องค์ประกอบจะถูกทำซ้ำและแสดงบนหน้าจอ