Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added CountSort Alogorithm in c++ #761

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
60 changes: 60 additions & 0 deletions Sorting/CountSort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// Function to perform counting sort
void countSort(vector<int> &arr)
{
// Find the minimum and maximum element in the array
int maxElement = *max_element(arr.begin(), arr.end());
int minElement = *min_element(arr.begin(), arr.end());

// Size of the range
int range = maxElement - minElement + 1;

// Create a count array to store the frequency of each element in the range
vector<int> count(range, 0);

// Store the count of each element in the count array
for (int i = 0; i < arr.size(); i++)
{
count[arr[i] - minElement]++;
}

// Overwrite the original array with sorted elements using the count array
int index = 0;
for (int i = 0; i < range; i++)
{
while (count[i] > 0)
{
arr[index++] = i + minElement;
count[i]--;
}
}
}

// Helper function to print the array
void printArray(const vector<int> &arr)
{
for (int num : arr)
{
cout << num << " ";
}
cout << endl;
}

int main()
{
vector<int> arr = {4, -2, 2, 8, 3, -3, 1};

cout << "Original array: ";
printArray(arr);

countSort(arr);

cout << "Sorted array: ";
printArray(arr);

return 0;
}