creatownpriorityqueue
by archit sir live sessionclass Heap { ArrayList<Integer> tree = new ArrayList<>(); void add(int val) { tree.add(val); upheapify(tree.size() - 1); } void upheapify(int idx) { if(idx == 0) return; int par = (idx - 1) / 2; if(tree.get(idx) < tree.get(par)) { Collections.swap(tree, idx, par); upheapify(par); } } } public class Main { public static void main(String[] args) { Heap pq = new Heap(); pq.add(50); System.out.println(pq.tree); pq.add(70); System.out.println(pq.tree); pq.add(60); System.out.println(pq.tree); pq.add(55); System.out.println(pq.tree); pq.add(65); System.out.println(pq.tree); pq.add(45); System.out.println(pq.tree); pq.add(48); System.out.println(pq.tree); pq.add(30); System.out.println(pq.tree); } }
Leave a Comment