xingbi-challenge/main.cpp
2024-11-03 04:29:16 -05:00

54 lines
1.8 KiB
C++

#include <algorithm>
#include <iostream>
#include <vector>
std::vector<std::size_t> getReversalsToSort(const std::vector<int> &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<std::size_t> getReversalsToSort(const std::vector<int> &arr) {
std::vector<int> intermediate = arr;
std::vector<std::size_t> ret = {};
for (std::size_t i = intermediate.size(); i > 1; i--) {
// only searching the unsorted elements
auto found =
std::max_element(intermediate.cbegin(), intermediate.cbegin() + i);
std::size_t first_swap = found - intermediate.cbegin() + 1;
std::size_t second_swap = i;
// remove false positives of elements already being in the correct spot
if (first_swap != second_swap) {
// if the element is already the first in the list we don't need to move
// it there
if (first_swap > 1) {
ret.push_back(first_swap);
std::reverse(intermediate.begin(), intermediate.begin() + first_swap);
}
ret.push_back(second_swap);
std::reverse(intermediate.begin(), intermediate.begin() + second_swap);
}
}
return ret;
}
int main(void) {
std::cout << "{";
std::vector<int> arr{12, 13, 11, 14};
for (auto &e : getReversalsToSort(arr)) {
std::cout << e << ",";
}
std::cout << "}\n";
}