HeapSort

Heapsort. Classical implementation


The heapsort method was discovered by english mathematician J.Williams. It's based on convenient numeration of binary tree vertices and association of tree with array.
Consider full binary tree with branches having height k. Such tree has 2(k+1) - 1 vertices (so dependence of tree's height on vertices number is approximately logarithmic). Really, the root vertex forms the zero layer of the tree, and then each horizontal layer has amount of vertices two times less then previous one. Layer number k consists 2k vertices. If we renumber vertices up to down and left to right, we'll see that vertex number s will be connected with vertexes 2s and 2s + 1 of the next layer (consider them as "children" of this vertex).
The hierarchical sorting is based on this way of numeration. Each array's index is associated with the single vertex, and array's items (let it h[1:n]) can be considered as vertices of binary tree. The sorting is performed in terms of this tree, the simple arithmetic connection of numbers of connected vertices lets to transform these items to indexes.
The sorting consist two phases. The first phase maintains hierarchical ordering of array: the value in each vertex must be not worse then values of children. Since sorting is traditionally performed by growth, we consider that "worse" means "more". For this purpose the sift operation will be used: the current item is compared with the worst child, and if child is worse then parent then the parent and child are swapped, and operation is repeated for item, that is now in child's place. All items from number [n/2] (why not n?) till number one are sifted in such manner.
The second sorting phase consist the sequental execution of next procedures: take the worst item (it stays now on the first place, but it must stay on the last one), swap it with the last one, decrease a number of tree vertices by disconnecting the last item, sift the first tree's item (to restore hierarchical ordering). In the end, when all items is disconnected from the tree, the array will be completely sorted.


Author: G.G. Udov. Supervisor: A.A. Shalyto

Saint-Petersburg State University of Information Technologies, Mechanics and Optics.
"Computer technologies" department

Source code

Copyright 2003 by Georgy G. Udov