Skip to content

Instantly share code, notes, and snippets.

@unwosu
Last active May 31, 2019 12:59
Show Gist options
  • Save unwosu/a0d840903309ac56e0e8a752b97d011d to your computer and use it in GitHub Desktop.
Save unwosu/a0d840903309ac56e0e8a752b97d011d to your computer and use it in GitHub Desktop.
counting sort with negative numbers
#include <iostream>
#include <vector>
#include <unordered_map>
#include <limits>
void counting_sort(vector<int> &v)
{
int n = v.size();
unordered_map<int, int> map;
int min = numeric_limits<int>::max();
int max = numeric_limits<int>::min();
for (auto &item : v)
{
if (item > max)
max = item;
if (item < min)
min = item;
auto got = map.find(item);
if (got == map.end())
{
map[item] = 0;
}
map[item]++;
}
int counter = 0;
for (int i = min; i <= max; i++)
{
auto cur = map.find(i);
if (cur != map.end())
{
for (int k = 0; k < cur->second; k++)
{
v[counter++] = cur->first;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment