2
0

heapsort.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (C) 2002-2005 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 pretent 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
  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