Last active
May 31, 2019 12:59
-
-
Save unwosu/a0d840903309ac56e0e8a752b97d011d to your computer and use it in GitHub Desktop.
counting sort with negative numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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