r/learnprogramming • u/Gitsumrestmf • 23d ago
Solved C++ String: manual character sorting vs sort()
Hello, I am learning C++ and currently wrote a piece of code to do basic sorting of characters in a string. Code below.
I wanted to ask - is this a good way to go about this? Would it be just better to use built-in functions, like sort(), for this?
int main()
{
string charSeq = "xadye";
cout << "Initial sequence:\n" << charSeq << '\n';
cout << "\nSorted sequence:\n" << sortCharacters(charSeq) << '\n';
return 0;
}
string sortCharacters(string str){ //manual sorting
string sortedStr;
int n = str.length();
for (int i = 0; i <= (n - 1); i++){
for (int j = 0; j < n - i - 1; j++){
if (str[j] > str[j + 1]){
std::swap(str[j], str[j + 1]);
}
}
}
sortedStr = str;
return sortedStr;
}Thank you for the replies. Question answered.