Data Structure --- heap sorting using C language
The process is shown in the figure below: (create a heap first, adjust, insert, and output)
Code:
// HeapSort // Yang Xin # include
# Include
// Heap adjustment, build a big top heap, arr [] is the array to be adjusted, and I is the position of the array to be adjusted // element, length is the length of the array void HeapAdjust (int arr [], int I, int length) {int Child; int temp; for (; 2 * I + 1 <length; I = Child) {// The Child node location = 2 * (parent node) + 1 Child = 2 * I + 1; // obtain the larger Child node if (Child <length-1 & arr [Child + 1]> arr [Child]) + + Child; // if a large Child node is greater than the parent node, move the large Child node up // replace its parent node if (arr [I] <arr [Child]) {temp = arr [I]; arr [I] = arr [Child]; arr [Child] = temp;} elsebreak ;}} // heap Sorting Algorithm void HeapSort (int arr [], int length) {int I; // adjust the first half element of the sequence, after the adjustment, the first element // is the largest element of the sequence. length/2-1 is the last non-leaf node for (I = length/2-1; I> = 0; -- I) HeapAdjust (arr, I, length); // adjust the sequence from the last element, keep narrowing down the Adjustment Scope until the first element // in the loop is to swap the first element with the current last element // ensure that the current last element is the current the maximum // of this sequence is constantly narrowing down and adjusting the heap range, after each adjustment, ensure that the first element is the largest element of the current sequence (I = length-1; I> 0; -- I) {arr [I] = arr [0] ^ arr [I]; arr [0] = arr [0] ^ arr [I]; arr [I] = arr [0] ^ arr [I]; HeapAdjust (arr, 0, I); // recursive adjustment} int main () {int I; int num [] = {98, 48,777, 63, 57,433, 23,111 2, 1 }; printf (============================= heap sorting ================== ); printf (essentially a Complete Binary Tree that uses the nature of the root node and subnode of the tree for sorting ); printf (====================================================== ); printf (the data to be sorted is :); for (I = 0; I <sizeof (num)/sizeof (int); I ++) {printf (% d, num [I]);} printf (); HeapSort (num, sizeof (num)/sizeof (int); printf (the sorted data is :); for (I = 0; I <sizeof (num)/sizeof (int); I ++) {printf (% d, num [I]);} printf (); return 0 ;}