#include #include #include std::vector getReversalsToSort(const std::vector &arr); /** * Imagine a sort algorithm, that sorts array of integers by repeatedly * reversing the order of the first several elements of it. * * For example, to sort [12,13,11,14], you need to reverse the order of the * first two (2) elements. You will get [13,12,11,14]. Then you shall reverse * the order of the first three (3) elements, and you will get [11,12,13,14] * * For this assignment you shall implement function * that returns list of integers corresponding to the required reversals. * E.g. for given vector [12,13,11,14] * the function should return [2, 3]. */ std::vector getReversalsToSort(const std::vector &arr) { // there's a slightly more fancy version of this but who cares // all we need is the elements sorted from least to greatest // sorting to get info might be cheating but eeeeeh it wasn't specified std::vector sorted = arr; std::sort(sorted.begin(), sorted.end()); std::vector ret = {}; // a bit more explicit than necessary but my brain thought it was useful info std::vector::const_iterator search_reference = arr.cbegin(); std::size_t i = arr.size(); for (auto elem = sorted.rbegin(); elem != sorted.rend(); elem++) { // using search reference so we don't find the same element over and over // again search_reference = std::find(search_reference, arr.cend(), *elem); std::size_t first_swap = search_reference - arr.cbegin() + 1; std::size_t second_swap = i; // remove false positives of elements already being in the correct spot // also remove cases where nothing changes in one of the reverses // (that should never happen) if (first_swap != second_swap && first_swap > 1 && second_swap > 1) { ret.push_back(first_swap); ret.push_back(second_swap); } i--; // pushing the search reference past what we just found so we don't find // it again if ((elem + 1) != sorted.rend() && *(elem + 1) == *elem) { search_reference++; } else { search_reference = arr.cbegin(); } } return ret; } int main(void) { std::cout << "{"; std::vector arr{12, 13, 11, 14}; for (auto &e : getReversalsToSort(arr)) { std::cout << e << ","; } std::cout << "}\n"; }