1 package sorts; 2 3 Import Java. util. arraylist; 4 Import Java. util. list; 5 import Java. util. random; 6 7 public class priorityqueue <t extends comparable <t> {// Min-heap 8 private list <t> heap = new arraylist <> (); 9 Private Static final int root_index = 0; 10 Private Static final int pre_root_index = root_index-1; 11 Public void offer (t obj) {12 heap. add (OBJ); // Add the last element 13 int Index = heap. size ()-1; // index of the last element 14 While (index> root_index) {// after adding an element to the heap, adjust the heap to make it another heap 15 Index = stepupheap (INDEX); // floating 16} 17} 18 private int stepupheap (INT index) {19 int parentindex = parent (INDEX); // obtain the index of the parent node 20 t element = heap. get (INDEX); 21 t parent = heap. get (parentindex); 22 if (parent. compareto (element)> 0) {// if the parent node is greater than the child node, 23 heap is switched. set (parentindex, element); 24 heap. set (index, parent); 25 return parentindex; // jump to parent index 26} else 27 return root_index; // do not need to switch 28} 29 public t poll () {30 if (isempty () 31 throw new runtimeexception (); 32 int Index = heap. size ()-1; // index of the last element 33 t least; 34 if (Index = 0) {35 least = heap. get (INDEX); 36 heap. remove (INDEX); 37} 38 else {39 t element = heap. get (INDEX); // obtain the last element 40 least = heap. get (root_index); // get the heap's root element 41 heap. set (root_index, element); // exchange the two elements 42 heap. set (index, least); 43 heap. remove (INDEX); // Delete the last element 44 stepdownheap (root_index); // sink the adjustment to make it heap 45 again} 46 Return least; 47} 48 private void stepdownheap (INT index) {49 int P = index; // parent 50 int lchild = lchild (p); // The left subnode 51 t temp = heap. get (p); 52 while (lchild
Priority queue-heap implementation