Data structure review notes-heap and heap sorting
Review the heap knowledge. Deep understanding
Heap sortingAndQuick sorting,Merge SortingThe same is a common sorting method with a time complexity of O (N * logN. Before learning about heap sorting, let's take a look at the binary heap.
Binary heap Definition
The binary heap is a complete binary tree or an approximate full binary tree.
The binary heap meets two features:
1. The key value of the parent node is always greater than or equal to (less than or equal to) the key value of any subnode.
2. The left and right subtree of each node are both a binary heap (both the maximum heap and the minimum heap ).
When the key value of the parent node is always greater than or equal to the key value of any child nodeMax heap. When the key value of the parent node is always less than or equal to the key value of any child nodeMinimum heap. Display a minimum heap:
Because there are few other heaps (such as the binary heap and the Fibonacci heap), the binary heap is generally referred to as the heap.
Heap Storage
Generally, the heap is represented by arrays. The subscript of the parent node of the I node is (I-1)/2. Its subnode subscript is 2 * I + 1 and 2 * I + 2 respectively. For example, the subnode subscripts of the first 0th nodes are 1 and 2 respectively.
Create a heap:
Typedef struct HeapStruct * MaxHeap; // create the maximum heap struct HeapStruct {ElementType * Elements;/* array of heap Elements */int Size; /* current number of heap elements */int Capacity;/* maximum heap Capacity */}; MaxHeap Create (int MaxSize) {/* Create an empty Max heap with MaxSize */MaxHeap H = malloc (sizeof (struct HeapStruct); H-> Elements = malloc (MaxSize + 1) * sizeof (ElementType); H-> Size = 0; H-> Capacity = MaxSize; H-> Elements [0] = MaxData; /* replace MaxData with MinData smaller than all the elements in the heap. It is also suitable for creating a minimum heap * // * defines that the "Sentinel" is greater than the value of all possible elements in the heap, facilitate later operations */return H ;}
Heap operation-insert and delete
<Span style = "font-size: 12px;"> void Insert (MaxHeap H, ElementType item) // algorithm: insert a new node into an ordered sequence from its parent node to the root node, which is faster than data exchange. {/* Insert the element item into the maximum heap. H, h-> Elements [0] has been defined as the sentry */int I; if (IsFull (H) {printf ("Max heap full"); return ;} I = ++ H-> Size;/* I points to the position of the last element in the heap after insertion */for (; H-> Elements [I/2] <item; i/= 2) H-> Elements [I] = H-> Elements [I/2];/* filter down nodes */H-> Elements [I] = item; /* Insert item */} Delete ElementType DeleteMax (Ma XHeap H) // Delete the maximum heap {/* retrieve the element with the largest key value from the maximum heap H and delete a node */int Parent, Child; ElementType MaxItem, temp; if (IsEmpty (H) {printf ("the maximum heap is empty"); return;} MaxItem = H-> Elements [1]; /* retrieve the maximum value of the root node * // use the last element in the max heap to filter the bottom node from the root node. */temp = H-> Elements [H-> Size --]; for (Parent = 1; Parent * 2 <= H-> Size; Parent = Child) {Child = Parent * 2; if (Child! = H-> Size) & (H-> Elements [Child] <H-> Elements [Child + 1]) Child ++; /* if (temp> = H-> Elements [Child]) break; else/* move the temp element to the next layer */H-> Elements [Parent] = H-> Elements [Child];} H-> Elements [Parent] = temp; return MaxItem ;}</span>
Illustration:
So far, we can get the establishment of the maximum heap:
Method 1: insert N elements one by one into a heap with initial null values. The maximum time cost is O (N logN ).
Create a maximum heap: store N existing elements in a one-dimensional array as required by the maximum heap.
Method 2: Create the maximum heap with linear time complexity.
(1) store N elements in the input order to meet the structure characteristics of a Complete Binary Tree.
(2) Adjust the location of each node to meet the ordered characteristics of the maximum heap.
Heap sorting
Reference Wikipedia directly here: it is more comprehensive than self-expression.
Demonstration of heap sorting algorithm. First, rearrange the elements to meet the heap conditions. In the figure, the structure of the heap tree is drawn simply before the sorting process.
First, we can see that 0th pieces of data in the heap are the smallest pieces of data in the heap after the heap is built. Retrieve the data and delete the heap. In this way, the 0th pieces of data in the heap are the smallest pieces of data in the heap. Repeat the above steps until only one piece of data in the heap is taken out directly.
Since the heap is simulated using arrays, after the array is heap, A [0] And A [n-1] are exchanged for the first time, and then A [0... N-2] restore the heap. For the second time, exchange A [0] with A [n-2], and then exchange A [0... N-3] restore the heap and repeat this operation until A [0] exchanges with A [1. Since every time the smallest data is merged into the next ordered interval, the entire array is sorted after the operation is complete, a bit similar to the selection of sorting.
# Include <iostream> using namespace std;/* # heap sorting # % # Array Implementation # % * // # filtering algorithm # % void sift (int d [], int ind, int len) {// # set I to the node to be filtered # % int I = ind; // # Left child who saves the I node in c # % int c = I * 2 + 1; // # The purpose of + 1 is to solve the problem that the left child of the node is always 0 since the node starts from 0 # % while (c <len) // # The leaf node is not filtered # % {// # If the node to be filtered has both left and right children, and the left child value is smaller than the right child # % // # select a large and record # % if (c + 1 <len & d [c] <d [c + 1]) c ++; // # exit if the value of the node to be filtered is greater than that of the left and right children. # % if (d [I]> d [c]) break; else {// # Switch # % int t = d [c]; d [c] = d [I]; d [I] = t; //// # reset the node to be filtered and the left child to be filtered # % I = c; c = 2 * I + 1 ;}} return ;} void heap_sort (int d [], int n) {// # initialize the heap. I starts from the last non-leaf node # % for (int I = (n-2) /2; I> = 0; I --) sift (d, I, n); for (int j = 0; j <n; j ++) {// # Switch # % int t = d [0]; d [0] = d [n-j-1]; d [n-j-1] = t; // # The filter number is 0 # % sift (d, 0, n-j-1);} int main () {int a [] = {3, 5, 3, 6, 4, 7, 5, 7, 4}; // # QQ # % heap_sort (a, sizeof (a)/sizeof (* )); for (int I = 0; I <sizeof (a)/sizeof (* a); I ++) {cout <a [I] <'';} cout <endl; return 0 ;}Worst case, time complexity:
In addition, note that heap sorting is unstable.