InsertionSort.h 1.5 KB

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