Heap sequencing is a feature that leverages the maximum (or minimum) of keywords in the maximum heap (or minimum heap) of heap records, making it easy to select the largest (or smallest) keyword in the current unordered region. Taking the maximum heap as an example, its basic idea is:
- First the initial file R[1..N] is built into a maximum heap, this heap is the initial unordered area;
- Then the most important record 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 the R[1..n-1].keys≤r[n].key;
- Because the new root r[1] may violate the heap nature, the current unordered area r[1..n-1] should be adjusted to a heap. 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[n1. N].keys, R[1..n-2] is also adjusted to the heap, and the operation is repeated until all is ordered.
The following is an example diagram:
1#include <stdio.h>2#include <stdlib.h>3 4 intN;5 6 /*7 * Build Heap8 */9 voidHeapadjust (int*array,intSintm)Ten { One inti; Aarray[0] =Array[s]; - for(i = s *2; I <= m; I *=2) - { the if(I < M && Array[i] < Array[i +1]) - { -i++; - } + if(! (array[0] <Array[i])) - { + Break; A } atArray[s] =Array[i]; -s =i; - } -Array[s] = array[0]; - } - in /* - * Heap Sorting to */ + voidHeapsort (int*Array) - { the inti; * for(i = n/2; i >0; i--) $ {Panax Notoginseng heapadjust (array, I, n); - } the for(i = n; i >1; i--) + { Aarray[0] = array[1]; thearray[1] =Array[i]; +Array[i] = array[0]; -Heapadjust (Array,1I1); $ } $ } - - intMain () the { - inti;Wuyi int*Array; theprintf"Please enter the size of the array:"); -scanf"%d", &n); WuArray = (int*)malloc(sizeof(int) * (n +1)); -printf"Please enter data (separated by spaces):"); About for(i =1; I <= N; i++) $ { -scanf"%d", &array[i]); - } - heapsort (array); Aprintf"after sorting is:"); + for(i =1; I <= N; i++) the { -printf"%d", Array[i]); $ } theprintf"\ n"); the}
Data structure sorting-heap sorting