Created
June 12, 2024 00:51
-
-
Save martin-minarik/52f614ae0616b8631c2ca743b26711df to your computer and use it in GitHub Desktop.
Distribution counting sort
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 <algorithm> | |
#include <functional> | |
using namespace std; | |
vector<int> distribution_counting_sort(vector<int> &array) { | |
int min_value = *min_element(array.begin(), array.end()); | |
int max_value = *max_element(array.begin(), array.end()); | |
vector<int> frequencies(max_value - min_value, 0); | |
vector<int> result(array.size()); | |
for (int &x: array) | |
frequencies[x - min_value] += 1; | |
for (int i = 1; i <= (max_value - min_value); ++i) | |
frequencies[i] += frequencies[i - 1]; | |
for (int j, i = (array.size() - 1); i >= 0; --i) { | |
j = array[i] - min_value; | |
result[frequencies[j] - 1] = array[i]; | |
frequencies[j] -= 1; | |
} | |
return result; | |
} | |
template<typename T> | |
void print_vector(vector<T> &array) { | |
for (T &value: array) | |
cout << value << " "; | |
cout << endl; | |
} | |
int main() { | |
vector<int> array{3, 5, 2, 7, 0, 1, 4}; | |
cout << "Distribution Counting Sort" << endl; | |
{ | |
vector<int> result = distribution_counting_sort(array); | |
cout << "Array:" << endl; | |
print_vector(array); // 3 5 2 7 0 1 4 | |
cout << "Sorted array:" << endl; | |
print_vector(result); // 0 1 2 3 4 5 7 | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment