Should I sort string characters myself or use std::sort?

November 18, 2026 4 answers
Asked by 3r+calvexo_527

I'm learning C++ and wrote a function that sorts the characters in a string by comparing and swapping neighbors. Is that a reasonable approach, or should I just use std::sort?

Answers

Vandrix-8q

For ordinary code, use std::sort. Include the algorithm header, then call std::sort(str.begin(), str.end()). It sorts the string in place, so you can print str afterward.

Writing your own is still a useful exercise. There just isn't much reason to maintain a custom sort for this task unless you have a specific need.

3r+calvexo_527:

Does that change the original string if I pass it to a function?

_c17+brindlepacket.4:

If the function takes the string by value, it sorts its own copy. If it takes a non-const reference, sorting changes the caller's string.

Reply to this answer
9t+glimmerwrench_275

What you've written is bubble sort. It's a good way to see how comparisons and swaps work, and you can practice explaining why each pass leaves another character in its final position.

Since your function already takes str by value and sorts that copy, you can return str directly. The extra sortedStr variable and assignment aren't needed.

Reply to this answer
4x!garnivo_836

The performance difference is worth understanding. Your nested passes take O(n squared) comparisons, even when the string is already sorted. std::sort has an O(n log n) comparison guarantee, which matters more as the input gets larger.

The swaps in your loop use constant extra space, but the function also makes a copy of the string because it takes the argument by value. Whether that copy is desirable depends on whether you want to preserve the original.

Reply to this answer
_x64!trembolo.5

One small gotcha: the default comparison sorts char values, not necessarily text in the order a person would expect. Uppercase and lowercase can be separated, and sorting the individual bytes of a UTF-8 string won't sort whole Unicode characters.

For a simple string of lowercase English letters, std::sort is a straightforward fit. For other text, decide what ordering you actually want first.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions