heapsort.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright (C) 2002-2012 Nikolaus Gebhardt
  2. // This file is part of the "Irrlicht Engine".
  3. // For conditions of distribution and use, see copyright notice in irrlicht.h
  4. #ifndef IRR_HEAPSORT_H_INCLUDED
  5. #define IRR_HEAPSORT_H_INCLUDED
  6. #include "irrTypes.h"
  7. namespace irr
  8. {
  9. namespace core
  10. {
  11. //! Sinks an element into the heap.
  12. template<class T>
  13. inline void heapsink(T*array, s32 element, s32 max)
  14. {
  15. while ((element<<1) < max) // there is a left child
  16. {
  17. s32 j = (element<<1);
  18. if (j+1 < max && array[j] < array[j+1])
  19. j = j+1; // take right child
  20. if (array[element] < array[j])
  21. {
  22. T t = array[j]; // swap elements
  23. array[j] = array[element];
  24. array[element] = t;
  25. element = j;
  26. }
  27. else
  28. return;
  29. }
  30. }
  31. //! Sorts an array with size 'size' using heapsort.
  32. template<class T>
  33. inline void heapsort(T* array_, s32 size)
  34. {
  35. // for heapsink we pretend this is not c++, where
  36. // arrays start with index 0. So we decrease the array pointer,
  37. // the maximum always +2 and the element always +1
  38. T* virtualArray = array_ - 1;
  39. const s32 virtualSize = size + 2;
  40. // build heap
  41. for (s32 i=((size-1)/2); i>=0; --i)
  42. heapsink(virtualArray, i+1, virtualSize-1);
  43. // sort array, leave out the last element (0)
  44. for (s32 i=size-1; i>0; --i)
  45. {
  46. const T t = array_[0];
  47. array_[0] = array_[i];
  48. array_[i] = t;
  49. heapsink(virtualArray, 1, i + 1);
  50. }
  51. }
  52. } // end namespace core
  53. } // end namespace irr
  54. #endif