Skip to content

Instantly share code, notes, and snippets.

@karliss
Last active November 29, 2017 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karliss/ebc27b0b2baa3e6fc0f50fadda733554 to your computer and use it in GitHub Desktop.
Save karliss/ebc27b0b2baa3e6fc0f50fadda733554 to your computer and use it in GitHub Desktop.
merge lists
//https://news.ycombinator.com/item?id=15804795#15804931
#include <algorithm>
#include <vector>
using intVectors = std::vector<std::vector<int> >;
std::vector<int> mergeLists(intVectors lists)
{
if (lists.empty()) return {};
while (lists.size() > 1) {
intVectors newLists;
newLists.reserve((lists.size() + 1)/2);
if (lists.size() % 2) {
newLists.push_back(std::move(lists.back()));
}
for (size_t i = 0; i + 1 < lists.size(); i++) {
auto &a = lists[i], &b = lists[i+1];
newLists.emplace_back(a.size() + b.size());
auto& mergedPair = newLists.back();
std::merge(a.begin(), a.end(),
b.begin(), b.end(),
mergedPair.begin());
newLists.push_back(std::move(mergedPair));
}
lists.swap(newLists);
}
return std::move(lists[0]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment