Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to implement heap sorting in C language

Shulou Source: shulou.com Published: 2022-06-02 07:38:12 09月23日 Update

This article introduces how to achieve heap sorting in c language, the content is very detailed, interested friends can use for reference, I hope it can be helpful to you.

The heap is a sequentially stored complete binary tree.

The keyword of each node is no larger than that of its child node, and such a heap is called a small root heap.

The keyword of each node is no less than that of its child node, and such a heap is called a big root heap.

For example, for the sequence of n elements {R0, R1, … , Rn} is called a heap if and only if one of the following relationships is satisfied:

(1) Ri = R2i+2 (big root pile)

Among them, iTunes 1, 2, … , nadir 2 rounded down

As shown in the figure above, the sequence R {3,5,8,10,7} is a typical small root heap.

There are two parent nodes in the heap, element 3 and element 8.

Element 3 is represented by R [0] in the array, and its left child node is R [1] and the right child node is R [2].

Element 5 is represented by R [1] in the array, its left child node is R [3], its right child node is R [4], and its parent node is R [0]. As you can see, they meet the following rules:

If the current element is represented by R [I] in the array, then

(1) its left child node is R [2i + 1]

(2) its right child node is: r [2i + 2]

(3) its parent node is: r [(iMel 1) / 2]

(4) R [I] 0; Imurb -) {/ / the last element and the first element are exchanged int temp = array [I]; array [I] = array [0]; array [0] = temp; / / filter array [0] node to get the heap HeapAdjust (array, 0, I) of 1 node. Printf ("% d trip:\ t", length-I); printPart (array, 0, length-1);} system ("pause"); return 0;} void HeapAdjust (int * array, int parent, int length) {int tmp = array [parent]; int Lchild= 2 * parent + 1; while (Lchild= array [Lchild]) break / assign the value of the child node to the parent node array [parent] = array [Lchild]; / / select the left child node of the child node, and continue to filter down parent = Lchild; Lchild = 2 * Lchild + 1;} array [parent] = tmp;} void printPart (int * array, int begin, int end) {for (int I = begin; I)

Tags: Node child element array sort key keyword sequence big root small root adjustment language two content more order processing help output good Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Linux Redmi macOS Shulou Information