Computer >> Máy Tính >  >> Lập trình >> Java

Max Heap trong Java

Max heap là một cây nhị phân hoàn chỉnh, trong đó giá trị của nút gốc ở mỗi bước lớn hơn hoặc bằng giá trị tại nút con.

Dưới đây là cách triển khai Max Heap bằng cách sử dụng các hàm thư viện.

Ví dụ

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());
   }
}

Đầu ra

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

Một lớp có tên Demo chứa chức năng chính. Bên trong hàm chính, một thể hiện của hàng đợi ưu tiên được xác định và các phần tử được thêm vào nó bằng cách sử dụng hàm ‘add’. Một trình lặp được xác định và nó

được sử dụng để lặp lại các phần tử trong hàng đợi ưu tiên. Hàm ‘thăm dò ý kiến’ được sử dụng để xóa một phần tử khỏi danh sách. Tiếp theo, các phần tử được lặp lại và hiển thị trên màn hình.