Data Structure Implementation

Previous page Contents

The heapsort algorithm works with a heaptree and a result list. They can be stored efficiently in one array.

Storing Heaptree and Result List in an Array

Heaptree and result list are stored together in one array. The array has as many elements as there are keys to sort. No additional storage space for pointers or intermediate results is needed. The beginning of the array is used by the heaptree, the remaining end by the result list (figure 1).

Array-Aufteilung
Figure 1: Heaptree and result list stored in one array

Providing Input Data

A program that wants to sort data with the heapsort algorithm provides it as an array. The array appears to the algorithm as a heaptree containing all keys. In the notation of figure 1 the green heaptree occupies the whole array. That is why the heaptree needs not be built but exists instantly, complete and completely filled.

Running the algorithm

The function heapsort performs the complete algorithm. Within the algorithm the function move-max moves keys from the heaptree to the result list. This removes one key from the heaptree which makes room in the array at the border between heaptree and result list. The result list grows using this free node and stores the new element there.

Providing Output Data

After the algorithm run the result list occupies the complete array. There is no need to copy this list, because the array can be used directly by the program.

Mapping Heaptree Nodes to Array Nodes

The heaptree root is stored at index 1 in the array.

For a node stored at index k in the array, its left child is stored at index 2*k and its right child at index 2*k+1 (figure 2). It follows that the parent node is at index (k div 2).

Mapping child nodes to indices
Figure 2: Mapping child nodes to indices

Figure 3 shows the array indices of the heaptree nodes for the heaptree used in the courseware.

Array indices of heaptree nodes
Figure 3: Array indices of heaptree nodes


You have now completed the main contents of the courseware. From the contents page you can reach exercises, where you can apply and test your new knowledge.


Previous page Contents