Data structure--implementation of the heap (bottom)

Source: Internet
Author: User

1, heap as priority queue application

For a normal queue, the nature of the FIFO, as long as the implementation of the team head delete elements, at the end of the team to insert elements. Therefore, the priority of such a queue can be considered as a measure of priority in the order in which the time arrives. The earlier you arrive, the higher the priority, the more prioritized the queue is dispatched.

More generally, many applications do not simply prioritize by time, such as by CPU time or other means ... In this case, it is easier to use the heap to express the priority queue.

2, Heap of two properties: ① Structural Properties--The heap is a completely binary tree from the structure. However, from the physical storage, the implementation of the heap is basically using a one-dimensional array to store all the nodes in the heap. ②ordering Property---This is determined by the definition of the heap, such as the large top heap: The value of the root node is greater than the value of the left and right children.

Because the heap has these two properties, the operation of the heap, such as insert operation, delete operation ... Both of these properties need to be maintained, so: This is why the heap insert, delete operations often need to be adjusted upward and downward, this is to maintain the heap of ordering property.

3, the analysis of time complexity of building heap

In the data structure-heap implementation (above), two methods of building the heap are analyzed, the time complexity is O (NLOGN) and the other is O (n). Now carefully analyze the following:

1 ImportJava.io.File;2 Importjava.io.FileNotFoundException;3 ImportJava.util.Scanner;4 5  Public classSort {6      Public Static voidMain (string[] args)throwsfilenotfoundexception{7Scanner sc =NewScanner (NewFile ("Inputfile"));//read Heap ' s element from Inputfile8         intn = sc.nextint ();//First line in the file gives number of integers to be read9Arraymaxheap<integer> sortHeap =NewArraymaxheap<integer>(n);Ten         //Build Heap One          for(inti = 0; I < n; i++) ASortheap.add (Sc.nextint ());//O (NLOGN) -          -         //Sort Phase the          while(!sortheap.isempty ()) - System.out.println (Sortheap.removemax ()); -     } -}

In the build operation above for loop, when the first element in the heap is added, the full binary tree height is 1, and the worst case where the Add method is called for heap adjustment takes Log1 time. When you add a second element, the full binary tree height is 2, and the worst case for heap adjustment takes log2 time ... When I add element I, the worst thing to do is to logi time for heap adjustments. Therefore, adding n elements to the heap takes time:

Log1 + log2 + log3 + ... + log (n-1) + Logn = log (1*2*3......*n) = Log n!

N! = (n/e) nsqrt (2N*PI)

So O (logn!) = O (Nlogn)

Similarly, you can analyze the heap ordering in the next while loop. Removemax () has a time complexity of logn,n as the number of elements in the current heap. So the time complexity of heap sorting is O (NLOGN)

As can be seen from here, this method of building the heap is implemented by invoking the interface of the heap definition. That is, call the heap's interface add () to implement.

Another way to build a heap is to directly manipulate the underlying storage of the heap---one-dimensional arrays to build the heap. This method builds the heap with a time complexity of O (n)

1integer[] arr =NewInteger[4];arr[0] = 20;arr[1] = 40;arr[2] = 30;arr[3] = 10;2Arraymaxheap<integer> HEAP2 =NewArraymaxheap<integer>(arr);3 4  Publicarraymaxheap (t[] entries) {5Heap = (t[])NewComparable[entries.length + 1];//How to use generic array ...6LastIndex =entries.length;7          for(intindex = 0; Index < entries.length; index++)8         {9Heap[index + 1] = Entries[index];//position No. 0 does not hold elementsTenSYSTEM.OUT.PRINTLN (Heap[index + 1]); One         } A          for(intindex = LASTINDEX/2; Index >= 1; index--) -Reheap (index);//call Reheap from the last non-leaf node to the root node for heap adjustment operations . -}

In the For loop on line 12th, starting with the last non-leaf node (LASTINDEX/2), call Reheap () to manipulate the integer array directly.

Private voidReheap (intRootindex) {        BooleanDone =false;//Mark Heap Adjustment completeT orphan =Heap[rootindex]; intLargechildindex = 2 * ROOTINDEX;//default left child's value is larger//heap adjustment is based on a subtree that is rooted in Largechildindex         while(!done && (Largechildindex <=LastIndex)) {            //Largechildindex labeled Rootindex The older children of the left and right children            intLeftchildindex = Largechildindex;//default left child's value is larger            intRightchildindex = Leftchildindex + 1; //Right child also exists, compare child            if(Rightchildindex <= lastIndex && (Heap[largechildindex].compareto (Heap[rightchildindex]) < 0)) Largechildindex=Rightchildindex; if(Orphan.compareto (Heap[largechildindex]) < 0) {Heap[rootindex]=Heap[largechildindex]; Rootindex=Largechildindex; Largechildindex= 2 * ROOTINDEX;//always default left child's value is larger            }            Else//the subtree with the roots of Rootindex is already in the heap.Done =true; } Heap[rootindex]=orphan; }

The pseudo-code for REHEAP is as follows:

Input:array a[0...n-1]output:max heap in a[0...n-1= n/2-1while (x>=0)    v= value at x    siftdown (v)    x=x-1endwhile

Analysis of the time complexity of O (n):

Assuming that the heap has a height of H, when a node is Reheap, a sub-tree with the root of that node needs to be adjusted downward. The root node is compared two times when adjusting downward (compared to the left and right children).

Therefore, assuming that a node is on layer I, 0<= i

Because it is a complete binary tree, the number of nodes in layer I is 2i

The total number of comparisons is: To remove the last layer of leaf node, the other layer of all the nodes of the comparison of the sum. Set total number of comparisons to S

Therefore, it is finally understood that the time complexity of this method of building the heap is O (n).

Reference: Data structure-implementation of the heap (i)

Data structure--implementation of the heap (bottom)

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.