Skip to content

Instantly share code, notes, and snippets.

@lnikon
Created August 9, 2018 20:17
Show Gist options
  • Save lnikon/0a94ab8a62d2405a1cfd246c3fbb83f2 to your computer and use it in GitHub Desktop.
Save lnikon/0a94ab8a62d2405a1cfd246c3fbb83f2 to your computer and use it in GitHub Desktop.
Counting sort.
template <class T>
auto countingSort(const std::vector<T>& vec)
{
if(vec.size() <= 1) std::move(vec);
std::vector<T> counts(vec.size(), 0);
const auto size = vec.size();
for(size_t i = 0; i < size - 1; ++i)
{
for(size_t j = i + 1; j < size; j++)
{
if(vec[i] < vec[j])
{
++counts[j];
}
else if(vec[i] > vec[j])
{
++counts[i];
}
}
}
std::vector<T> result(vec.size());
for(size_t i = 0; i < size; ++i)
{
result[counts[i]] = vec[i];
}
return std::move(result);
}
int main()
{
std::vector<int> vec {-4, 3, 1, -6, -1, -9, 3, 5, 12, 64, 23, 4, 12 };
auto result = countingSort(vec);
for(const auto& item: result)
{
std::cout << item << ' ';
}
std::cout << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment