/** * Clayton Cafiero * CS 2240 * 21-Jan-2021 */ #include #include #include #include template void printVector(const std::vector& v) { for (Comparable item : v) { std::cout << item << " "; } std::cout << std::endl; } /** * Radix sort * Note: Not a templated function * This assumes a vector of three-letter strings with values a-z */ void radixSort(std::vector& v, int numChars) { std::vector> buckets(26); // We work from right to left for (int iteration = numChars - 1; iteration >= 0; --iteration) { // Copy items from vector into the appropriate buckets for (int i = 0; i < v.size(); ++i) { // ASCII chars a - z have underlying int values of // 97 (a) - 122 (z) int bucket = (int)v[i][iteration] - (int)'a'; buckets[bucket].push_back(v[i]); } // Copy everything from buckets back into vector in the appropriate order int i = 0; for (int bucket = 0; bucket < buckets.size(); ++bucket) { for (int item = 0; item < buckets[bucket].size(); ++item) { v[i] = buckets[bucket][item]; ++i; } buckets[bucket].clear(); } printVector(v); } } /** * Assumes a vector of three-character strings with chars a-z */ void radixSort(std::vector& v) { const int numChars = 3; radixSort(v, numChars); } int main() { std::vector v = {"wig", "cog", "mug", "bib", "arm", "boy", "add", "coy", "who", "axe", "doe", "dot", "say", "rip", "new", "elm", "hog", "awe"}; printVector(v); radixSort(v); }