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
63 changes: 48 additions & 15 deletions sorting/counting_sort_string.cpp
Original file line number Diff line number Diff line change
@@ -1,33 +1,66 @@
// C++ Program for counting sort
#include <iostream>

#include <string>
#include <vector>
using namespace std;

void countSort(string arr) {
string output;
void countSort(string& arr) {
int n = static_cast<int>(arr.length());

// Handle edge cases first
if (n == 0) {
cout << "Empty String\n";
return;
}

if (n == 1) {
cout << "Already Sorted " << arr << '\n';
return;
}

int count[256], i;
for (int i = 0; i < 256; i++) count[i] = 0;
// output string preallocated with correct size
string output(n, '\0');

for (i = 0; arr[i]; ++i) ++count[arr[i]];
// use 256 for all possible unsigned char values
vector<int> count(256, 0);

for (i = 1; i < 256; ++i) count[i] += count[i - 1];
// store count of each character
for (int i = 0; i < n; ++i) {
++count[static_cast<unsigned char>(arr[i])];
}

for (i = 0; arr[i]; ++i) {
output[count[arr[i]] - 1] = arr[i];
--count[arr[i]];
// change count[i] so that count[i] now contains actual
// position of this character in output
for (int i = 1; i < 256; ++i) {
count[i] += count[i - 1];
}

for (i = 0; arr[i]; ++i) arr[i] = output[i];
// build the output array (iterate from end for stable sort)
for (int i = n - 1; i >= 0; --i) {
unsigned char ch = static_cast<unsigned char>(arr[i]);
int pos = count[ch] - 1; // position index in output
output[pos] = arr[i];
--count[ch];
}

cout << "Sorted character array is " << arr;
// copy output to arr
arr = output;
cout << "Sorted character array is " << arr << '\n';
}

int main() {
string arr;
cin >> arr;
string s1 = "hello";
countSort(s1); // Sorted character array is ehllo

string s2 = "AaBbZz012";
countSort(s2); // Sorted character array is 012ABZabz

countSort(arr);
string s3 = "";
countSort(s3); // Empty String

string s4 = "x";
countSort(s4); // Already Sorted x

return 0;
}