Home | Namespaces | Hierarchy | Alphabetical List | Class list | Files | Namespace Members | Class members | File members | Tutorials

# heapsort.h

Go to the documentation of this file.

    00001 // Copyright (C) 2002-2009 Nikolaus Gebhardt
    00002 // This file is part of the "Irrlicht Engine".
    00003 // For conditions of distribution and use, see copyright notice in irrlicht.h
    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) // there is a left child
    00020         {
    00021                 s32 j = (element<<1);
    00022
    00023                 if (j+1 < max && array[j] < array[j+1])
    00024                         j = j+1; // take right child
    00025
    00026                 if (array[element] < array[j])
    00027                 {
    00028                         T t = array[j]; // swap elements
    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         // for heapsink we pretent this is not c++, where
    00044         // arrays start with index 0. So we decrease the array pointer,
    00045         // the maximum always +2 and the element always +1
    00046
    00047         T* virtualArray = array_ - 1;
    00048         s32 virtualSize = size + 2;
    00049         s32 i;
    00050
    00051         // build heap
    00052
    00053         for (i=((size-1)/2); i>=0; --i)
    00054                 heapsink(virtualArray, i+1, virtualSize-1);
    00055
    00056         // sort array
    00057
    00058         for (i=size-1; i>=0; --i)
    00059         {
    00060                 T t = array_[0];
    00061                 array_[0] = array_[i];
    00062                 array_[i] = t;
    00063                 heapsink(virtualArray, 1, i + 1);
    00064         }
    00065 }
    00066
    00067 } // end namespace core
    00068 } // end namespace irr
    00069
    00070 #endif
    00071

| The Irrlicht Engine Documentation © 2003-2010 by Nikolaus Gebhardt. Generated on Sun Feb 14 13:06:56 2010 by Doxygen (1.6.2)