Go to the documentation of this file.00001 
00002 
00003 
00004 
00005 #ifndef __IRR_HEAPSORT_H_INCLUDED__
00006 #define __IRR_HEAPSORT_H_INCLUDED__
00007 
00008 #include "irrTypes.h"
00009 
00010 namespace irr
00011 {
00012 namespace core
00013 {
00014 
00016 template<class T>
00017 inline void heapsink(T*array, s32 element, s32 max)
00018 {
00019     while ((element<<1) < max) 
00020     {
00021         s32 j = (element<<1);
00022 
00023         if (j+1 < max && array[j] < array[j+1])
00024             j = j+1; 
00025 
00026         if (array[element] < array[j])
00027         {
00028             T t = array[j]; 
00029             array[j] = array[element];
00030             array[element] = t;
00031             element = j;
00032         }
00033         else
00034             return;
00035     }
00036 }
00037 
00038 
00040 template<class T>
00041 inline void heapsort(T* array_, s32 size)
00042 {
00043     
00044     
00045     
00046 
00047     T* virtualArray = array_ - 1;
00048     s32 virtualSize = size + 2;
00049     s32 i;
00050 
00051     
00052 
00053     for (i=((size-1)/2); i>=0; --i)
00054         heapsink(virtualArray, i+1, virtualSize-1);
00055 
00056     
00057     for (i=size-1; i>0; --i)
00058     {
00059         T t = array_[0];
00060         array_[0] = array_[i];
00061         array_[i] = t;
00062         heapsink(virtualArray, 1, i + 1);
00063     }
00064 }
00065 
00066 } 
00067 } 
00068 
00069 #endif
00070