Priority queue-heap implementation

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.