diff --git a/sorting/counting_sort_string.cpp b/sorting/counting_sort_string.cpp index 69d80c18a32..9f04b230e73 100644 --- a/sorting/counting_sort_string.cpp +++ b/sorting/counting_sort_string.cpp @@ -1,33 +1,66 @@ // C++ Program for counting sort #include - +#include +#include using namespace std; -void countSort(string arr) { - string output; +void countSort(string& arr) { + int n = static_cast(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 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(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(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; } +