Sort.h 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #pragma once
  2. #include <array>
  3. #include <utility>
  4. template<typename T, size_t N>
  5. void MergeGrow(std::array<T, N>& arr, int mfirst, int half, int msecond)
  6. {
  7. if (msecond - mfirst == 0) return;
  8. int first = mfirst - 1, second = msecond - 1;//êîððåêòèðîâêè âõîäíûõ çíà÷åíèé ñ ó÷åòîì íóìåðàöèè â ìàññèâå
  9. if (second - first == 1) {
  10. if (arr[first] > arr[second]) { std::swap(arr[first], arr[second]); }
  11. return;
  12. }
  13. int i = 0;
  14. std::array<T, N> tmp{};
  15. int start_half = half;
  16. while (i <= msecond - mfirst)
  17. {
  18. if (first >= start_half || half <= second && arr[first] >= arr[half])
  19. {
  20. tmp[i] = arr[half];
  21. half++;
  22. }
  23. else {
  24. tmp[i] = arr[first];
  25. first++;
  26. }
  27. i++;
  28. }
  29. int tmpi = 0;
  30. for (size_t arri = mfirst - 1; arri < msecond; arri++) {
  31. arr[arri] = tmp[tmpi];
  32. tmpi++;
  33. }
  34. }
  35. //Ðåàëèçàöèÿ ïðèâåäåííîãî â ïñåâäîêîäå ôðàãìåíòà
  36. template<typename T, size_t N>
  37. void Sort(std::array<T, N>& arr, int first, int second)
  38. {
  39. if (first < second)
  40. {
  41. int half = (first + second) / 2;
  42. Sort(arr, first, half);
  43. Sort(arr, half + 1, second);
  44. MergeGrow(arr, first, half, second);//Ascending
  45. }
  46. }