[Programming Pearl] Chapter 1 heap (sorting, priority queue)

Source: Internet
Author: User

1. Heap

1) Heap: A Complete Binary Tree with the value of any node less than or equal to the value of its child is a small root heap.

A Complete Binary Tree with values of any node greater than or equal to the value of its child is a big root heap.

To facilitate the use of the full binary tree, the array starts with subscript 1.

This way: leftchild = 2 * I;

Rightchild = 2 * I + 1;

Parent = I/2;

Null I <1 or I> N


2) Heap algorithm analysis

The worst time complexity of heap sorting is O (nlogn ). The average performance of heap sequence is closer to the worst performance.

Because the initial heap requires a large number of comparisons, the heap sorting is not suitable for files with a small number of records.

Heap sorting is local sorting, and the auxiliary space is O (1)

Heap sorting is unstable.

3) Heap implementation

[Note]The heap is not necessarily a full binary tree, but generally uses a full binary tree, which is mainly used for storage and operation. Heap sorting applies to Arrays

                                  

Initial build heap:

Give an array and regard the array as a Complete Binary Tree.

From the last non-leaf node (length/2, subscript starts from 1) to the first node A [1], adjust and create the heap.

Sorting and heap Adjustment

Swap the first value a [1] with the last value, and then adjust the heap for a [1] (at this time, the array length is adjusted to length-1)


[Note] Here, the initial heap building only considers that there are n elements, and you can adjust the heap building down.

But what should I do with insert (t? The heap policy is adjusted upwards. See priority queue for details.

4) source code

# Include "stdio. H "inline void swap (Int & A, Int & B) {int temp = A; A = B; B = temp;} void heapadjust (INT array [], int I, int nlength) // top-down heap adjustment {int nchild; int ntemp; // assign a value to the node to be adjusted for (ntemp = array [I]; 2 * I <nlength; I = nchild) // 2 * I <nlength indicates that there are left children {nchild = 2 * I; // left child/* get a larger one if two subnodes in total */If (nchild <nLength-1 & array [nchild + 1]> array [nchild]) // nchild <The nLength-1 determines that the header is not + nchild;/* If the larger child node is greater than the parent node, adjust the child node to the parent node */If (ntemp <array [nchild]) array [I] = array [nchild]; else break; // if this field is not added, an error will occur. The first will output the second array [nchild] = ntemp; // The child node is equal to the parent node (without running break)} void heapsort (int A [], int length) {/* Initial heap */For (INT I = length/2; I> 0; -- I) // adjust from the last non-leaf node (here I is a subscript) heapadjust (A, I, length); For (INT I = length; I> 1; -- I) {swap (A [1], a [I]); /* swap the first largest element with the last one */heapadjust (A, 1, I); // adjust the heap (note length = I because the heap is gradually becoming smaller )}} int main () {int A [10] = {,}; heapsort (A, 8); For (INT I = 1; I <9; I ++) printf ("% d \ n", a [I]); Return 0 ;}


Ii. priority queue

1) The priority queue is a set of 0 or more elements, each element has a priority or value, and the operations performed on the priority queue have 1) Search; 2) Insert a new element; 3) Delete.

In Min priorityq u e, the search operation is used to search for the element with the smallest priority and the delete operation is used to delete the element;

For Max priority queue, the search operation is used to search for the element with the highest priority, and the delete operation is used to delete the element.

The elements in the priority queue can have the same priority. The search and delete operations can be performed based on any priority.

2) implement priority queue

Initialize an array, insert elements to the empty array in sequence, and adjust the heap every time an element is inserted.

Delete the element, exchange the first element with the last element, and adjust the heap downward.

3) code implementation

# Include <iostream> using namespace STD; Template <class T> class priqueue {PRIVATE: INTN, maxsize; T * X; void swap (Int & I, Int & J) // exchange the array element value {T = I; I = J; j = T;} public: priqueue (INT m) // initialize the Array {maxsize = m; X = new T [maxsize + 1]; n = 0;} void insert (t) {int I, P; X [++ N] = T; // Insert the element to the end of the for (I = N; I> 1 & X [p = I/2]> X [I]; I = P) swap (X [p], X [I]);} t extractmin () // adjust the heap downward {int I, C; t = x [1]; X [1] = x [n --]; for (I = 1; (C = 2 * I) <= N; I = C) {If (C + 1 <= N & X [C + 1] <X [c]) C ++; If (X [I] <= x [c]) break; swap (X [c], X [I]);} return t;} void print (int n) {for (INT I = 1; I <N; I ++) // output heap cout <X [I] <"" ;}}; template <class T> void pqsort (T V [], int N) // Initialize an array first, and then insert and create a heap {priqueue <t> PQ (n); int I; for (I = 0; I <n; I ++) PQ. insert (V [I]); cout <"output sorted heap:"; PQ. print (n) ;}int main () {const INTN = 10; Inti, V [N]; /* Create a heap with 10 elements by adjusting the heap up */for (I = 0; I <n; I ++) V [I] = n-I; pqsort (v, n); cout <"\ n: insert and delete operations (input 0 indicates the minimum value for deletion, input others indicates insertion)" <Endl; priqueue <int> PQ (100); int COUNT = 0; while (CIN> I) if (I = 0) {If (count) cout <"the smallest element to be deleted is:" <PQ. extractmin () <"\ n"; else cout <"insert an element first" <Endl;} else {PQ. insert (I); count ++;} return 0 ;}

Iii. Exercise

1) In order to increase the speed of adjusting the heap up, place the Sentinel = the currently inserted element in X [0. Saving the need to judge I> 1 every time

Adjust the heap upwards to end: X [p] <= x [I]

 

Void insert (t) // adjust the heap up {int I, P; X [++ N] = T; // put the inserted element to the last X [0] = T; for (I = N; X [p = I/2]> X [I]; I = P) Swap (X [p], X [I]);}

4) A. when constructing the Harman tree, you need to select the two minimum values of the current array, delete the two minimum values, and insert the sum of the calculation into the original array.

Use the heap, create the heap, and call the minimum value function twice. After calculating the sum, call insert heap and adjust heap


B. Adding a smaller floating point number and a larger floating point number may cause loss of precision. Therefore, the minimum two values are used together. Insert and the array set. The last one is the sum of all floating point numbers.


C. Typical topk


D. combine the current values of all small files into a heap.

Take the minimum heap value and insert the sorting array. Adjust the heap. Insert the next element of the small file (if there is no successor, do not operate)


5) The remaining capacity is a heap, And the weights are inserted to the heap in ascending order.


6) ask for advice (not understanding)


7) Please advise (not understanding)



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.