The heap sort does not require massive recursion or multiple arrays to work. This makes it an attractive option for very large data sets of millions of items.

The heap sort works as it name suggests – it begins by building a heap out of the data set, and then removing the largest item and placing it at the end of the sorted array. After removing the largest item, it reconstructs the heap and removes the largest remaining item and places it in the next open position from the end of the sorted array. This is repeated until there are no items left in the heap and the sorted array is full. Elementary implementations require two arrays – one to hold the heap and the other to hold the sorted elements.

To do an in-place sort and save the space the second array would require, the algorithm below “cheats” by using the same array to store both the heap and the sorted array. Whenever an item is removed from the heap, it frees up a space at the end of the array that the removed item can be placed in.

### Heap Sort Routine

// array of integers to hold values private int[] a = new int[100]; // number of elements in array // Heap Sort Algorithm for( i = (x/2)-1; i >= 0; i– ) for( i = x-1; i >= 1; i– ) public void siftDown( int root, int bottom ) while( (root*2 <= bottom) && (!done) ) if( a[root] < a[maxChild] ) |

You can download the full code here, or the compiled code here.

further : http://www.publicjoe.f9.co.uk/

## Leave a Reply