Skip to content

Commit

Permalink
Partition Two sorts
Browse files Browse the repository at this point in the history
  • Loading branch information
danngreen committed Jan 7, 2025
1 parent 3e510c2 commit d718863
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions util/partition.hh
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,30 @@ struct PartitionTwo {
FixedVector<unsigned, MaxElements> b{};

PartitionTwo(std::span<unsigned> vals) {
struct IdVal {
unsigned val;
unsigned id;
};

FixedVector<IdVal, MaxElements> ordered;
for (auto val : vals) {
ordered.push_back({val, (unsigned)ordered.size()});
}

std::ranges::sort(ordered, std::greater{}, &IdVal::val);

unsigned a_sum = 0;
unsigned b_sum = 0;

// The part with the smaller sum gets the next element
for (auto i = 0u; auto val : vals) {
for (auto [val, i] : ordered) {
if (a_sum <= b_sum) {
a_sum += val;
a.push_back(i);
} else {
b_sum += val;
b.push_back(i);
}
i++;
}
}
};

0 comments on commit d718863

Please sign in to comment.