InsertionSort.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // SPDX-FileCopyrightText: 2022 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. JPH_NAMESPACE_BEGIN
  5. /// Implementation of the insertion sort algorithm.
  6. template <typename Iterator, typename Compare>
  7. inline void InsertionSort(Iterator inBegin, Iterator inEnd, Compare inCompare)
  8. {
  9. // Empty arrays don't need to be sorted
  10. if (inBegin != inEnd)
  11. {
  12. // Start at the second element
  13. for (Iterator i = inBegin + 1; i != inEnd; ++i)
  14. {
  15. // Move this element to a temporary value
  16. auto x = std::move(*i);
  17. // Check if the element goes before inBegin (we can't decrement the iterator before inBegin so this needs to be a separate branch)
  18. if (inCompare(x, *inBegin))
  19. {
  20. // Move all elements to the right to make space for x
  21. Iterator prev;
  22. for (Iterator j = i; j != inBegin; j = prev)
  23. {
  24. prev = j - 1;
  25. *j = *prev;
  26. }
  27. // Move x to the first place
  28. *inBegin = std::move(x);
  29. }
  30. else
  31. {
  32. // Move elements to the right as long as they are bigger than x
  33. Iterator j = i;
  34. for (Iterator prev = j - 1; inCompare(x, *prev); j = prev, --prev)
  35. *j = std::move(*prev);
  36. // Move x into place
  37. *j = std::move(x);
  38. }
  39. }
  40. }
  41. }
  42. /// Implementation of insertion sort algorithm without comparator.
  43. template <typename Iterator>
  44. inline void InsertionSort(Iterator inBegin, Iterator inEnd)
  45. {
  46. std::less<> compare;
  47. InsertionSort(inBegin, inEnd, compare);
  48. }
  49. JPH_NAMESPACE_END