#ifndef INVERSIONS_HPP_
#define INVERSIONS_HPP_

#include <vector>

namespace inversions {
namespace details {

int _nlogn(std::vector<int>& list) {

    if (list.size() < 2)
        return 0;

    int count = 0;

    std::vector<int>::iterator middle = list.begin();
    std::advance(middle, list.size() / 2);

    std::vector<int> left(list.begin(), middle);
    std::vector<int> right(middle, list.end());

    count += _nlogn(left);
    count += _nlogn(right);

    std::vector<int>::size_type i = 0, j = 0, k = 0;
    while (i < left.size() and j < right.size()) {
        if (left[i] <= right[j]) {      // Elements are already sorted.
            list[k] = left[i];
            i++;
        } else {                        // Elements were in reverse order.
            count += left.size() - i;   // Increment the inversion count.
            list[k] = right[j];
            j++;
        }
        k++;
    }

    // Put the remaining elements in the original list.
    if (i == left.size()) {
        while (k != list.size())
            list[k++] = right[j++];
    } else {
        while (k != list.size())
            list[k++] = left[i++];
    }

    return count;
}

}   // namespace details

int nlogn(std::vector<int> list) {
    return details::_nlogn(list);
}

int quadratic(const std::vector<int>& list) {

    if (list.size() < 2)
        return 0;

    int count = 0;
    std::vector<int>::size_type i;
    for (i = 0; i < list.size() - 1; ++i) {
        std::vector<int>::size_type j;
        for (j = i + 1; j < list.size(); ++j) {
            if (list[i] > list[j]) {
                count++;
            }
        }
    }
    return count;
}

}   // namespace inversions

#endif /* INVERSIONS_HPP_ */