Data Structure --- implement heap sorting by c language --- sort by c heap
The process is shown in the figure below: (create a heap first, adjust, insert, and output)
Code:
// HeapSort // Yang Xin # include <stdio. h> # include <stdlib. h> // 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 =========================\ n" ); printf ("essentially a Complete Binary Tree, sorting by the root node \ n of the tree and the nature of the subnode \ n "); printf ("========================================== = \ n "); printf ("the data to be sorted is \ n"); for (I = 0; I <sizeof (num)/sizeof (int); I ++) {printf ("% d", num [I]);} printf ("\ n"); HeapSort (num, sizeof (num)/sizeof (int )); printf ("the sorted data is \ n"); for (I = 0; I <sizeof (num)/sizeof (int); I ++) {printf ("% d", num [I]);} printf ("\ n"); return 0 ;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.