seems to work correctly now, can be swapped to pull max ratherthan using a sorted array

This commit is contained in:
Pagwin 2024-11-03 02:32:05 -05:00
parent 5d27449f2f
commit 76bd3dbbfa
No known key found for this signature in database
GPG key ID: 81137023740CA260

View file

@ -24,35 +24,32 @@ std::vector<std::size_t> getReversalsToSort(const std::vector<int> &arr) {
std::vector<int> sorted = arr;
std::sort(sorted.begin(), sorted.end());
std::vector<int> intermediate = arr;
std::vector<std::size_t> ret = {};
// a bit more explicit than necessary but my brain thought it was useful info
std::vector<int>::const_iterator search_reference = arr.cbegin();
std::size_t i = arr.size();
std::size_t i = intermediate.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);
// only searching the unsorted elements
auto found =
std::find(intermediate.cbegin(), intermediate.cbegin() + i, *elem);
std::size_t first_swap = search_reference - arr.cbegin() + 1;
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
// 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);
if (first_swap != second_swap) {
// also remove reverses where nothing changes
if (first_swap > 1) {
ret.push_back(first_swap);
std::reverse(intermediate.begin(), intermediate.begin() + first_swap);
}
if (second_swap > 1) {
ret.push_back(second_swap);
std::reverse(intermediate.begin(), intermediate.begin() + 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;