Heap (max heap): The heap is a complete binary tree. The values of all non-leaf nodes in the tree are not smaller than those of other child nodes. The principle of heap sorting is to use the heap nature. After an element is inserted to generate a heap, the elements removed from the heap (the root node of the tree) are the largest elements in the heap. In the following implementation, a linear array is allocated for heap space. The array stores the connector pointer, And the array size is the connector count plus 1, [1... N] the connector pointer in the heap. [0] the connector pointer in and out of the heap. During Heap insertion, the connector pointer is first stored in the array [0] bits, and the root node is compared by comparing the parent node at the insert position, until the parent node greater than the node is found, and then the node is inserted in the Child location. In the process of deleting the heap, the top element [1] to [0] is retrieved in sequence, the connector is removed from the heap, and the first part of the connection list is inserted, then, merge the elements at the bottom of the heap into the [0] bits, re-adjust the heap, start from the root node, and search for its Gemini nodes in sequence until the child nodes smaller than the node are found, then insert the node in the parent location. The comparison of connector values is implemented through the callback function. Xdl_api void heapsortlink (linkptr root, linksortcall PF, void * parm );
/**//*
Function: Performs heap sorting on the linked list.
Parameter: Root is the root connector pointer, PF is the sort callback function, And Param is the callback parameter.
Return: None
*/
// Adjust the inbound heap
Void _ adjustinsert (linkptr * pA, int N, linksortcall PF, void * parm)
...{
While (n> 1 & (* PF) (PA [0], pa [n/2], parm)> 0)
...{
Pa [N] = pa [n/2];
N/= 2;
}
Pa [N] = pa [0];
}
// Output heap Adjustment
Void _ adjustdelete (linkptr * pA, int N, linksortcall PF, void * parm)
...{
Int I;
I = 2;
While (I <= N)
...{
If (I <n & (* PF) (PA [I], pa [I + 1], parm) <0)
I ++;
If (* PF) (PA [0], pa [I], parm)> = 0)
Break;
Pa [I/2] = pa [I];
I * = 2;
}
Pa [I/2] = pa [0];
}
// Heap sorting
Void heapsortlink (linkptr root, linksortcall PF, void * parm)
...{
Linkptr * pA;
Int count, I;
Linkptr PLK;
Count = linkcount (Root );
If (count <2)
Return;
// Alloc heap for sorting link nodes
Pa = (linkptr *) xdlalloc (count + 1, sizeof (linkptr ));
// Insert into heap
PLK = getfirstlink (Root );
For (I = 1; I <= count; I ++)
...{
Pa [0] = PLK;
_ Adjustinsert (Pa, I, PF, parm );
PLK = getnextlink (PLK );
}
// Delete from heap, then order insert into Link List
While (count)
...{
PLK = pa [1];
Insertlink (root, link_first, deletelink (root, PLK ));
Pa [0] = pa [count];
Count --;
_ Adjustdelete (Pa, Count, PF, parm );
}
// Free heap
Xdlfree (PA );
}
Collected by barenx