### The Heap Sort Algorithm

• Sorting an array using a Heap structure

• Problem description:

• Given an array of values.

For example:

 ``` [6.4, 2.5, 9.2, 3.5, 8.9, 1.1, 7.5, 4.2] ```

• How can we sort the values

 ``` [1.1, 2.5, 3.5, 4.2, 6.4, 7.5, 8.9, 9.2] ```

using a Heap ???

• Fact:

• The smallest value in a Heap is always stored in the root node !!!

Example:

The root noode has the smallest value (1)

Therefore:

 We can get the values in sorted order if we keep deleting the root node from a Heap !!!

• Pseudo code of using a Heap to sort an array a[ ]:

 ``` /* ================================================ Store all the values in a Heap ================================================ */ for ( i = 0; i < a.length; i++ ) insert a[i] into a heap; /* ================================================ Always remove the smallest value from the Heap ! ================================================ */ for ( i = 0; i < a.length; i++ ) { r = delete the root node from the heap; // root ALWAYS has // the smallest value !! Print (r); } ```

• Java program:

 ``` public static void main(String[] args) { Scanner in = new Scanner(System.in); double a[] = {1.1, 2.5, 3.5, 4.2, 6.4, 7.5, 8.9, 9.2}; Heap x = new Heap( 100 ); for ( int i = 0; i < a.length; i++ ) { System.out.println("Insert: " + a[i] ); x.put( a[i] ); x.printHeap(); } System.out.println("\n\nKeep removing the first node : "); for ( int i = 0; i < a.length; i++ ) { double r; r = x.remove(1); System.out.print( r + ", "); } System.out.println(); } ```

Output:

 ``` Keep removing the first node : 1.1, 2.5, 3.5, 4.2, 6.4, 7.5, 8.9, 9.2, ```

The output is sorted !!!

• Example Program: (Demo above code)

How to run the program:

 Right click on link and save in a scratch directory To compile:   javac testProg.java To run:          java testProg