#pragma once

#include <vector>
#include <hack/logger/logger.hpp>

// Сортировка вставкой
// Эффективна на мелких массивах. Сложнгость O(N^2)
namespace alg
{
  inline void merge(std::vector<int>& v, int left, int mid, int right, std::vector<int>& tmp) 
  {
    for(int i = left, j = mid + 1; left <= right; ++left)
    {
      bool useRight = i > mid || (j <= right && tmp[j] < tmp[i]);
      v[left] = tmp[(useRight ? j : i)++];
    }
  }

  inline void merge_sort_helper(std::vector<int>& v, int left, int right, std::vector<int>& tmp) 
  {
    if (left < right) 
    {
      int mid = (left + right) / 2;

      merge_sort_helper(tmp, left, mid, v);
      merge_sort_helper(tmp, mid + 1, right, v);

      merge(v, left, mid, right, tmp);
    }
  }

  inline void merge_sort(std::vector<int>& v)
  {
    std::vector<int> tmp(v);
    merge_sort_helper(v, 0, v.size() - 1, tmp);
  }
}

