#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
using std::string;
// function to get maximum string of characters
size_t getMaximum(string dum[], int n){
size_t max = dum[0].size();
for (int i = 1; i < n; i++){
if (dum[i].size()>max)
max = dum[i].size();
}
return max;
}
void countSort(string a[], int size, size_t k){
string *b = NULL; int *c = NULL;
b = new string[size];
c = new int[257];
for (int i = 0; i <257; i++){
c[i] = 0;
}
for (int j = 0; j <size; j++){
c[k < a[j].size() ? (int)(unsigned char)a[j][k] + 1 : 0]++;
}
for (int f = 1; f <257; f++){
c[f] += c[f - 1]; // ASCII conversion
}
for (int r = size - 1; r >= 0; r--){
b[c[k < a[r].size() ? (int)(unsigned char)a[r][k] + 1 : 0] - 1] = a[r];
c[k < a[r].size() ? (int)(unsigned char)a[r][k] + 1 : 0]--;
}
for (int l = 0; l < size; l++){
a[l] = b[l];
}
// memory destroy
delete[] b; // unaddress the pointer b
delete[] c; // unaddress the pointer c
}
// function to sort the array of strings of characters
void radixSort(string holder[], int res){
size_t max = getMaximum(holder, res);
for (size_t digit = max; digit > 0; digit--){ // size_t is unsigned, so avoid using digit >= 0, which is always true
countSort(holder, res, digit - 1);
}
}
int main(void) {
cout<<"-----------Radix Sort-----------\n";
cout<<"1 - Perform Radix Sort\n";
cout<<"2 - Exit: \n";
cout<<"Your choice>>";
int choice;
cin>>choice;
if(choice==1){
cout<<"How many items you want to add: ";
int num;
cin>>num;
string data[num];
string st;
for(int i=0;i<num;i++){
printf("Enter %d item :",(i+1));
cin>>st;
data[i]=st;
}
puts("These are your Strings of characters before Radix Sort");
for (size_t i = 0; i < sizeof(data) / sizeof(data[0]); i++) {
printf(" %s\n", data[i].c_str());
}
puts("Processing ..");
puts("Sorting start");
puts("Sorting ....");
radixSort(data, (int)(sizeof(data) / sizeof(data[0]))); // Radix Sort Function call
puts("Sorting ....");
puts("Sorting ....");
puts("Sorting ....");
puts("Sorting ....");
puts("Sorting ....");
puts("Sorting ....");
puts("Done Sucessfully ....");
puts("These are your Strings of characters after Radix Sort");
for (size_t i = 0; i < sizeof(data) / sizeof(data[0]); i++) {
printf(" %s\n", data[i].c_str());
}}else if(choice==2){
return 0;
}
return 0;
}
Puvaan 0 Newbie Poster
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.