Notes on Heapsort

CS 510: Computer Algorithms

Heapsort


Efficient Space Implementation

If we look at an array implementation of a heapsort, there is a clever space efficiency we can use that will also lead to a better graphical representation of the heapsort in the animation applet.

Building the Heap:

 Step One:
   Raw Data:	3  14  6  8  9  41  5  2  16  7  12
		|
		v
   Heap Array:	3


 Step Two:
   Raw Data:	x  14  6  8  9  41  5  2  16  7  12
		    |
		    v
   Heap Array:	3  14


 Step Three:
   Raw Data:	x  xx  6  8  9  41  5  2  16  7  12

		  /\ 
		 v  v
   Heap Array:	14  3


 Step Four:
   Raw Data:	x  xx  6  8  9  41  5  2  16  7  12
		       |
		       v
   Heap Array:	14  3  6


 Step Five:
   Raw Data:	x  xx  x  8  9  41  5  2  16  7  12
		          |
		          v
   Heap Array:	14  3  6  8


 Step Six:
   Raw Data:	x  xx  x  x  9  41  5  2  16  7  12
		      ___
		     /   \ 
		    v     v
   Heap Array:	14  8  6  3

Conclusion:

At each step, we take one element out of the Raw Data list while we add one element to the Heap array. We could store both the initial data and the heap in the same array.


Building the Sorted List:

 Step One:
		   _____________________________
		  /     			\ 
		 v				 \
   Heap Array:	41  16  14  9  12  6  5  2  3  7  8
		|
		v
      Biggest:	41
			  _
			 / \ 
			v   v
      Intermed. Heap:	8  16  14  9  12  6  5  2  3  7  xx
			      ________
			     /        \ 
			    v          v
      Intermed. Heap:	16  8  14  9  12  6  5  2  3  7  xx

      New Heap Array:	16  12  14  9  8  6  5  2  3  7  xx

      Sorted List:	                                 41


 Step Two:
		   __________________________
		  /     		     \ 
		 v			      \
   Heap Array:	16  12  14  9  8  6  5  2  3  7  xx
		|
		v
      Biggest:	16
			  _____
			 /     \ 
			v       v
      Intermed. Heap :	7  12  14  9  8  6  5  2  3  x  xx

      New Heap Array:	14  12  7  9  8  6  5  2  3  x  xx

      Sorted List:	                             16  41


Conclusion:

At each step, we take one element out of the Heap array while we add one element to the Sorted List. We could store both the heap and the final sorted list in the same array. Putting this together with the previous conclusion we see that we can do all of the heapsort processing in one array.



CS 510 Home

News

Homework

Class Projects

Class Notes

Syllabus

Bibliography