Heap sorting (C #)
The heap data structure is an array object, which can be regarded as a Complete Binary Tree.
Complete Binary Tree)
If the height of a binary tree is set to H, except for layer H, the other layers (1 ~ H-1) are all reached the maximum number of points, the H layer of all nodes are continuously concentrated on the leftmost, This Is The Complete Binary Tree.
The full binary tree is derived from the full binary tree. For a binary tree with a depth of K and N nodes,
It is called a Complete Binary Tree only when each of its nodes is one-to-one pairs of nodes numbered from 1 to n in a full binary tree with a depth of K.
(Full Binary Tree)
For a node I in the heap, if it has left and right sons, the left son left (I) index (starting from 0) is I * 2 + 1,
The index of right son right (I) is I * 2 + 2, and the index of the parent node of node I is (I-1)/2.
The Code is as follows:
/// <Summary> /// minimum heap sorting (ascending) /// </Summary> Public static int [] minheapsort (INT []) {// construct the array as the minimum heap bucket minheap (a); int alenght =. length; int heapsize = alenght; int [] sorttedarray = new int [. length]; for (INT I = 0; I <alenght; I ++) {// retrieve the minimum value of the root node sorttedarray [I] = A [0]; A [0] = A [heapsize-1]; minheapify (A, 0, heapsize --);} return sorttedarray ;} /// <summary> /// construct the array as the minimum heap // </Summary> P Ublic static void bucket minheap (INT [] A) {for (INT I =. length/2-1; I> = 0; I --) {minheapify (A, I,. length) ;}}/// <summary> // adjust the binary heap, adjust the binary tree with I as the root node to the minimum heap // </Summary> Public static void minheapify (INT [] A, int I, int heapsize) {int left = I * 2 + 1; // The left son index int right = I * 2 + 2; // The right son index int mivvalueindex = I; // Save the minimum value of the index if (left <peapsize & A [I]> A [left]) {// If the left son is smaller than the current node, record the index of the Son, As the minimum value index mivvalueindex = left;} If (right <peapsize & A [mivvalueindex]> A [right]) {// The right son is smaller than the current node, then the record is the son's index, which is used as the minimum index mivvalueindex = right;} If (mivvalueindex! = I) {// switch root and subnode values int temp = A [I]; A [I] = A [mivvalueindex]; A [mivvalueindex] = temp; // recursively process the subtree minheapify (A, mivvalueindex, heapsize );}}