fork(14) download
  1. #include <utility>
  2. #include <cstdlib>
  3.  
  4. template<class T>
  5. constexpr void swap(T& l, T& r)
  6. {
  7. T tmp = std::move(l);
  8. l = std::move(r);
  9. r = std::move(tmp);
  10. }
  11.  
  12. template <typename T, size_t N>
  13. struct array
  14. {
  15. constexpr T& operator[](size_t i)
  16. {
  17. return arr[i];
  18. }
  19.  
  20. constexpr const T& operator[](size_t i) const
  21. {
  22. return arr[i];
  23. }
  24.  
  25. constexpr const T* begin() const
  26. {
  27. return arr;
  28. }
  29. constexpr const T* end() const
  30. {
  31. return arr + N;
  32. }
  33.  
  34. T arr[N];
  35. };
  36.  
  37. template <typename T, size_t N>
  38. constexpr void sort_impl(array<T, N> &array, size_t left, size_t right)
  39. {
  40. if (left < right)
  41. {
  42. size_t m = left;
  43.  
  44. for (size_t i = left + 1; i<right; i++)
  45. if (array[i]<array[left])
  46. swap(array[++m], array[i]);
  47.  
  48. swap(array[left], array[m]);
  49.  
  50. sort_impl(array, left, m);
  51. sort_impl(array, m + 1, right);
  52. }
  53. }
  54.  
  55. template <typename T, size_t N>
  56. constexpr array<T, N> sort(array<T, N> array)
  57. {
  58. auto sorted = array;
  59. sort_impl(sorted, 0, N);
  60. return sorted;
  61. }
  62.  
  63. constexpr array<int, 11> unsorted{5,7,3,4,1,8,2,9,0,6,10}; // odd number of elements
  64. constexpr auto sorted = sort(unsorted);
  65.  
  66. #include <iostream>
  67. int main()
  68. {
  69. std::cout << "unsorted: ";
  70. for(auto const& e : unsorted)
  71. std::cout << e << ", ";
  72. std::cout << '\n';
  73.  
  74. std::cout << "sorted: ";
  75. for(auto const& e : sorted)
  76. std::cout << e << ", ";
  77. std::cout << '\n';
  78. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
unsorted: 5, 7, 3, 4, 1, 8, 2, 9, 0, 6, 10, 
sorted: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,