#include <utility>
#include <cstdlib>
template<class T>
constexpr void swap(T& l, T& r)
{
T tmp = std::move(l);
l = std::move(r);
r = std::move(tmp);
}
template <typename T, size_t N>
struct array
{
constexpr T& operator[](size_t i)
{
return arr[i];
}
constexpr const T& operator[](size_t i) const
{
return arr[i];
}
constexpr const T* begin() const
{
return arr;
}
constexpr const T* end() const
{
return arr + N;
}
T arr[N];
};
template <typename T, size_t N>
constexpr void sort_impl(array<T, N> &array, size_t left, size_t right)
{
if (left < right)
{
size_t m = left;
for (size_t i = left + 1; i<right; i++)
if (array[i]<array[left])
swap(array[++m], array[i]);
swap(array[left], array[m]);
sort_impl(array, left, m);
sort_impl(array, m + 1, right);
}
}
template <typename T, size_t N>
constexpr array<T, N> sort(array<T, N> array)
{
auto sorted = array;
sort_impl(sorted, 0, N);
return sorted;
}
constexpr array<int, 11> unsorted{5,7,3,4,1,8,2,9,0,6,10}; // odd number of elements
constexpr auto sorted = sort(unsorted);
#include <iostream>
int main()
{
std::cout << "unsorted: ";
for(auto const& e : unsorted)
std::cout << e << ", ";
std::cout << '\n';
std::cout << "sorted: ";
for(auto const& e : sorted)
std::cout << e << ", ";
std::cout << '\n';
}
I2luY2x1ZGUgPHV0aWxpdHk+CiNpbmNsdWRlIDxjc3RkbGliPgoKdGVtcGxhdGU8Y2xhc3MgVD4KY29uc3RleHByIHZvaWQgc3dhcChUJiBsLCBUJiByKQp7CiAgICBUIHRtcCA9IHN0ZDo6bW92ZShsKTsKICAgIGwgPSBzdGQ6Om1vdmUocik7CiAgICByID0gc3RkOjptb3ZlKHRtcCk7Cn0KCnRlbXBsYXRlIDx0eXBlbmFtZSBULCBzaXplX3QgTj4Kc3RydWN0IGFycmF5CnsKICAgIGNvbnN0ZXhwciBUJiBvcGVyYXRvcltdKHNpemVfdCBpKQogICAgewogICAgICAgIHJldHVybiBhcnJbaV07CiAgICB9CgogICAgY29uc3RleHByIGNvbnN0IFQmIG9wZXJhdG9yW10oc2l6ZV90IGkpIGNvbnN0CiAgICB7CiAgICAgICAgcmV0dXJuIGFycltpXTsKICAgIH0KCiAgICBjb25zdGV4cHIgY29uc3QgVCogYmVnaW4oKSBjb25zdAogICAgewogICAgICAgIHJldHVybiBhcnI7CiAgICB9CiAgICBjb25zdGV4cHIgY29uc3QgVCogZW5kKCkgY29uc3QKICAgIHsKICAgICAgICByZXR1cm4gYXJyICsgTjsKICAgIH0KCiAgICBUIGFycltOXTsKfTsKCnRlbXBsYXRlIDx0eXBlbmFtZSBULCBzaXplX3QgTj4KY29uc3RleHByIHZvaWQgc29ydF9pbXBsKGFycmF5PFQsIE4+ICZhcnJheSwgc2l6ZV90IGxlZnQsIHNpemVfdCByaWdodCkKewogICAgaWYgKGxlZnQgPCByaWdodCkKICAgIHsKICAgICAgICBzaXplX3QgbSA9IGxlZnQ7CgogICAgICAgIGZvciAoc2l6ZV90IGkgPSBsZWZ0ICsgMTsgaTxyaWdodDsgaSsrKQogICAgICAgICAgICBpZiAoYXJyYXlbaV08YXJyYXlbbGVmdF0pCiAgICAgICAgICAgICAgICBzd2FwKGFycmF5WysrbV0sIGFycmF5W2ldKTsKCiAgICAgICAgc3dhcChhcnJheVtsZWZ0XSwgYXJyYXlbbV0pOwoKICAgICAgICBzb3J0X2ltcGwoYXJyYXksIGxlZnQsIG0pOwogICAgICAgIHNvcnRfaW1wbChhcnJheSwgbSArIDEsIHJpZ2h0KTsKICAgIH0KfQoKdGVtcGxhdGUgPHR5cGVuYW1lIFQsIHNpemVfdCBOPgpjb25zdGV4cHIgYXJyYXk8VCwgTj4gc29ydChhcnJheTxULCBOPiBhcnJheSkKewogICAgYXV0byBzb3J0ZWQgPSBhcnJheTsKICAgIHNvcnRfaW1wbChzb3J0ZWQsIDAsIE4pOwogICAgcmV0dXJuIHNvcnRlZDsKfQoKY29uc3RleHByIGFycmF5PGludCwgMTE+IHVuc29ydGVkezUsNywzLDQsMSw4LDIsOSwwLDYsMTB9OyAvLyBvZGQgbnVtYmVyIG9mIGVsZW1lbnRzCmNv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