🏗️」 wip(ex02): algo is basically done now i think ? just need some optimisations iirc

This commit is contained in:
2025-08-30 16:23:35 +02:00
parent c8a3c731c3
commit f41fe7846d

View File

@@ -33,19 +33,22 @@ std::vector<size_t> generateJacobsthal(size_t n)
return seq;
}
template <typename T>
struct Pair {
T first;
T second;
};
template <typename Container, typename T>
typename Container::iterator binaryInsertPosition(Container &c, const T &value)
{
typename Container::iterator first = c.begin();
typename Container::iterator last = c.end();
template <typename T>
struct PairComp {
bool operator()(const Pair<T> &x, const Pair<T> &y) const
{
return x.second < y.second;
while (first < last)
{
typename Container::iterator mid = first + (last - first) / 2; //tzvetan told me a better way iirc but i don't remember D:
if (*mid < value)
first = mid + 1;
else
last = mid;
}
};
return first;
}
template <typename Container>
Container fordJohnsonSort(const Container &input)
@@ -56,7 +59,7 @@ Container fordJohnsonSort(const Container &input)
if (input.size() <= 1)
return input;
std::vector<Pair<T> > pairs;
std::vector<std::pair<T, T> > pairs;
size_t i = 0;
for (; i + 1 < input.size(); i += 2)
{
@@ -64,16 +67,16 @@ Container fordJohnsonSort(const Container &input)
T b = input[i+1];
if (a > b)
std::swap(a, b);
Pair<T> p;
p.first = a;
p.second = b;
pairs.push_back(p);
pairs.push_back(std::make_pair(a, b));
}
std::sort(pairs.begin(), pairs.end(), PairComp<T>());
Container larger;
for (size_t j = 0; j < pairs.size(); ++j)
larger.push_back(pairs[j].second);
for (size_t k = 0; k < pairs.size(); ++k)
result.push_back(pairs[k].second);
larger = fordJohnsonSort(larger);
result = larger;
std::vector<size_t> order = generateJacobsthal(pairs.size());
std::vector<bool> inserted(pairs.size(), false);
@@ -83,8 +86,7 @@ Container fordJohnsonSort(const Container &input)
size_t j = order[idx];
if (j < pairs.size() && !inserted[j])
{
typename Container::iterator pos = std::lower_bound(
result.begin(), result.end(), pairs[j].first);
typename Container::iterator pos = binaryInsertPosition(result, pairs[j].first);
result.insert(pos, pairs[j].first);
inserted[j] = true;
}
@@ -94,8 +96,7 @@ Container fordJohnsonSort(const Container &input)
{
if (!inserted[j])
{
typename Container::iterator pos = std::lower_bound(
result.begin(), result.end(), pairs[j].first);
typename Container::iterator pos = binaryInsertPosition(result, pairs[j].first);
result.insert(pos, pairs[j].first);
}
}
@@ -103,7 +104,7 @@ Container fordJohnsonSort(const Container &input)
if (i < input.size())
{
T leftover = input[i];
typename Container::iterator pos = std::lower_bound(result.begin(), result.end(), leftover);
typename Container::iterator pos = binaryInsertPosition(result, leftover);
result.insert(pos, leftover);
}