heapsort.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. s32 virtualSize = size + 2;
  40. s32 i;
  41. // build heap
  42. for (i=((size-1)/2); i>=0; --i)
  43. heapsink(virtualArray, i+1, virtualSize-1);
  44. // sort array, leave out the last element (0)
  45. for (i=size-1; i>0; --i)
  46. {
  47. T t = array_[0];
  48. array_[0] = array_[i];
  49. array_[i] = t;
  50. heapsink(virtualArray, 1, i + 1);
  51. }
  52. }
  53. } // end namespace core
  54. } // end namespace irr
  55. #endif