Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 71 additions & 19 deletions Sorting/Counting Sort/C++/Couting_Sort.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,78 @@

using namespace std;

void countingSort(vector<int> &v) {
int range = *max_element(begin(v), end(v));
vector<int> cnt(range + 1, 0);
for (int i = 0; i < (int)v.size(); ++i) {
++cnt[v[i]];
}

for (int i = 0, j = -1; i <= range; ++i) {
for (int k = 0; k < cnt[i]; ++k) {
v[++j] = i;
}
// Find the maximum element in the array.

int findMax(int arr[], int n)
{
int maxi = INT_MIN;
for (int i = 0; i < n; i++)
{
maxi = arr[i] > maxi ? arr[i] : maxi;
}
return maxi;
}

void countingSort(int arr[], int n)
{
int range = findMax(arr, n) + 1;

// Initialize an array to store the frequency of every element in the array.

int count[range] = {0};

// Counting the occurence of each element.

for (int i = 0; i < n; ++i)
{
count[arr[i]]++;
}

for (int i = 1; i <= range; i++)
{
count[i] += count[i - 1];
}

// Rotate the array left by one element.

for (int i = range; i > 0; i--)
{
count[i] = count[i - 1];
}
count[0] = 0;

// Declare an array to store the sorted elements.

int output[n];

for (int i = 0; i < n; i++)
{
output[count[arr[i]]] = arr[i];
count[arr[i]]++;
}

// Arrage the output elements in original array.

for (int i = 0; i < n; i++)
{
arr[i] = output[i];
}
}

int main() {
vector<int> v{10, 10, 20, 30, 12, 8, 9, 14, 13, 11};
countingSort(v);
for (int i = 0; i < (int)v.size(); ++i) {
cout << v[i] << " ";
}
cout << "\n";
return 0;
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
countingSort(arr, n);
for (int i = 0; i < n; ++i)
{
cout << arr[i] << " ";
}
cout << "\n";
return 0;
}