Priority queue and minimum heap Max heap

Source: Internet
Author: User

Why the default queue is the heap implementation, the default is the high priority of the team, the definition of the structure of the weight load function in order from small to large? It turns out that I don't know much about the priority queue:

1 Stacks1.1 Introduction

n A sequence of keywords kl,k2,...,kn called (heap), when and only if the sequence satisfies the following properties (for short, heap properties):

(1) ki<=k (2i) and Ki<=k (2i+1) (1≤i≤n), of course, this is the small Gan, Dagen is replaced by the >= number. K (i) is the non-leaf node of the two-fork tree, K (2i) is the left child, K (2i+1) is the right child

If the vector stored in this sequence is R[1..N] as a storage structure of a complete binary tree , the heap is essentially a complete binary tree that satisfies the following properties:

The keywords of any non-leaf nodes in the tree are not greater than (or not less than) the keywords of their left and right children (if any) nodes.

1.2 The height of the heap

A heap can be thought of as a tree, and the height of the node in the heap can be defined as the top of the longest simple descent path from this node to the leaf node, and the height of the heap is defined as the height of the tree root. We will see that some of the basic operations on the heap structure run at most of the time in proportion to the height of the tree, O (LGN).

1.3 Heap Sorting

Heap sequencing takes advantage of the maximum (or minimum) keyword of the Dagen (or small Gan) heap top record, making it easy to select the maximum (or minimum) number of keywords in the current unordered region.

(1) The basic idea of sorting with Dagen

① the initial file R[1..N] into a large heap, this heap is the initial unordered area

② R[1] (that is, the top of the heap) and the last record of the unordered zone R[n] exchange, resulting in a new unordered area r[1..n-1] and ordered area R[n], and meet R[1..n-1].keys≤r[n].key

③ the current unordered area r[1..n-1] should be adjusted to a heap because the new root r[1] may violate the heap nature because of the exchange. Then again, the largest record of the r[1..n-1] r[1] and the last record of the interval r[n-1] exchange, resulting in a new unordered area R[1..n-2] and ordered area r[n-1. N], and still satisfies the relationship r[1..n-2].keys≤r[n-1. N].keys, R[1..n-2] will also be adjusted to the heap.

......

Until there is only one element in the unordered area.

(2) Basic operation of Dagen sorting algorithm:

① initialization operation: R[1..N] is constructed as the initial heap;

② the basic operation of each order: the heap top record of the current unordered area r[1] and the last record of the interval are exchanged, then the new unordered area is adjusted to the heap (also known as the Rebuild heap).

Attention:

① only need to do n-1 sequencing, select a larger n-1 keyword that can make the file increment order.

② with small Gan is similar to the use of a large root heap, except that the ordered result is descending and orderly. Heap sorting and direct selection sorting are reversed: The unordered area is always before the ordered area in the heap order at any time, and the ordered area is at the end of the original vector from the rear

1.4 Algorithm Analysis

The time of the heap sequencing consists mainly of the time overhead of building the initial heap and rebuilding the heap repeatedly, both of which are implemented by invoking Heapify.

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

Heap sorting is not appropriate for files with fewer records due to the number of comparisons required to build the initial heap.

The heap sort is in-place sort, the secondary space is O (1),

It is an unstable sort method.

1.5 Algorithm Implementation

To r[l the initial file: N] to a large heap, you must adjust the subtree in its corresponding full binary tree to the heap as the root of each node.

< Span style= "FONT-FAMILY:SIMSUN; Font-size:14px "> Obviously only one node of the tree is a heap, and in a complete binary tree, all the nodes with a number greater than n/2 are leaves, so the subtree with these nodes as root are already heaps. In this way, we only need to sequentially adjust the nodes with the ordinal n/2,...,1 as the root subtree to the heap.

 #include <iostream> using namespace std;  const int MAX = 100;      typedef struct SQLIST {int R[max];  int length;  }sqlist;    typedef sqlist Heaptype; void Heapadjust (Heaptype &h, int s, int m) {//known h.r[s: M] records the keyword except h.r[s] to meet the definition of the heap, this function adjusts h.r[s]//keyword, so that h.r[s.      M] becomes a small top heap (for keywords recorded in it) int rc = H.r[s];          for (int j = 2 * s; j <= m; J *= 2)//filter down for children with larger values {if (J < m && H.r[j] < h.r[j+1])          {+ + j;//j is the subscript for a record with a greater value} if (RC >= h.r[j]) {BREAK;//RC should be inserted on position s          } H.r[s] = H.r[j];      s = j; } H.r[s] = rc;//Insert} void Heapsort (Heaptype &h) {//heap sort for order table H for (int i = H.LENGTH/2; i > 0 ;      --I)//put h.r[1..h.length] into the heap, here is to make each node is a heap, because the point is greater than N/2 is the leaf node, is the heap {heapadjust (h,i,h.length);    } for (int i = h.length; i > 1;---i) {int tmp = h.r[1];//The last record in the heap top record and the current unsorted subsequence H.R[1..I] is exchanged with each other      H.R[1] = H.r[i];            H.r[i] = tmp;      Heapadjust (H, 1, i-1);//resize h.r[1..i-1] to heap}} int main () {Heaptype H;      H.R[1] = 4;      H.R[2] = 3;      H.R[3] = 5;      H.R[4] = 1;      H.R[5] = 6;      H.R[6] = 2;      H.length = 6;      Heapsort (H);      for (int i = 1; I <= h.length; + + i) {cout << h.r[i] << "";      } cout << Endl;  return 0;  }

2 Priority Queue2.1 Introduction

The queue is characterized by FIFO. Usually the queue is likened to the line to buy things, everyone is very orderly, first line people first buy things. But the priority queue is different, it does not follow the FIFO rule, but based on the priority of the elements in the queue, priority is first taken out. The priority queue is often likened to real-life printing. A print shop has a lot of printers, each machine performance is different, some printers print quickly, and some printers printing speed is very slow. When these printers continue to print their own tasks on the line to enter the waiting state. If I were to print a file at this time, I chose not the first printer to queue, but the best, the fastest printer.

Focus: Priority queue, is to see priority, who priority is higher, who will get permissions first. Not in the order of queuing!

Basic operation:

Empty () returns true if the queue is null

Pop () Delete the top element

Push () joins an element

Size () returns the number of elements owned in the priority queue

Top () returns priority queue to top element

In the default priority queue, high priority first-out team. In the default int type, the first team is the larger number.

2.2 Implementing priority queues with heaps

The following is the priority queue for the minimum heap implementation:

#include <iostream> #include <vector> using namespace std;      Class Heap {public:heap (int isize);        ~heap ();      int Enqueue (int ival);      int Dequeue (int &ival);      int getmin (int &ival);  void PrintQueue ();      Protected:int *m_pdata;      int m_isize;  int m_iamount;  };      heap::heap (int isize = 100)//Note here is starting from 0, so if the root is I, then the left child is 2*i+1, the right child is 2*i+2 {m_pdata = new int[isize];      M_isize = isize;  M_iamount = 0;  } heap::~heap () {delete []m_pdata;      } int heap::enqueue (int ival)//Enter Heap {if (M_iamount = = m_isize) {return 0;      } M_pdata[m_iamount + +] = ival;      int iIndex = m_iamount-1; while (M_pdata[iindex] < m_pdata[(iIndex-1)/2])//float until the minimum heap {swap (m_pdata[iindex],m_pdata[(iIndex-1) is satisfied          )/2]);      IIndex = (iIndex-1)/2;  } return 1;      } int Heap::D equeue (int &ival)//Out Heap {if (M_iamount = = 0) {return 0; } ival = M_pdata[0];//out the heap data m_pdata[0] = m_pdata[m_iamount-1];//The last data on top of the first root--m_iamount;//total minus 1 int rc = M_pdata      [0];      int s = 0; for (int j = 2*s +1; j < M_iamount; J *= 2)//After the last number is placed in the first position, start sinking to maintain the nature of the heap {if (J < M_iamount-1 &          & M_pdata[j] > M_pdata[j+1]) {+ + J;          } if (RC < m_pdata[j])//RC should be inserted in the S position {break;          } M_pdata[s] = M_pdata[j];      s = j;      } M_pdata[s] = RC;  return 1;      } int heap::getmin (int &ival) {if (M_iamount = = 0) {return 0;      } ival = m_pdata[0];  return 1; void Heap::p rintqueue () {for (int i = 0; i < M_iamount; + + i) {cout << m_pdata[i] <      < "";  } cout << Endl;      } int main () {heap heap; Heap.      Enqueue (4); Heap.      Enqueue (1); Heap.      Enqueue (3); Heap.      Enqueue (2); Heap.      Enqueue (6); Heap.   Enqueue (5);   Heap.printqueue ();      int ival; Heap.      Dequeue (ival); Heap.        Dequeue (ival);      Heap.printqueue ();  return 0;  }

2.3 STL Implementation Priority Queue

How to use:

Header file:

#include <queue>

How to declare:

1. Common method:

priority_queue<int>q;
By manipulating the elements from the large to the small order of the team

2. Custom Priority:

struct CMP  {      bool operator () (int x, int y)      {          return x > y;      }  };

//Where the second parameter is a container type. The third parameter is a comparison function. Structure declaration method:
struct node{      int x, y;       friend bool Operator < (Node A, Node B)      {             return a.x > b.x;//struct, x small priority      }};
priority_queue<node>q;//Definition Method
In this structure, Y is the value and X is the priority.
The priority in the element is compared by customizing the operator< operator.
It is best not to overload ">" When Overloading "<", a compilation error may occur3 Applications

First priority queue is implemented by the heap, so in the future to use the priority queue, can be directly implemented in C + + STL directly, but it is best to implement a few times, otherwise we will only become a fool, what things will know how to use, do not know how to achieve.

The priority queue is a wide range of applications, such as:

1. Construct Huffman Code

Constructing Huffman encoding is to find two points with the least frequency in the node collection, and then merge the nodes into the collection, then loop ...

2. Some task scheduling algorithms

For example, the operating system of the thread scheduling algorithm, there are priority to schedule, each time the higher priority of the thread

3. Merge n ordered files into an ordered file

First, the first element of N ordered files is taken out, placed in the priority queue, and then take the minimum value, and then insert the element Guide priority queue, take the minimum value ...

4, because the priority queue internal is a heap implementation, so applicable to the heap are applicable to the priority queue

such as sorting, find the median, find the largest number of K



Priority queue and minimum heap Max heap

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.