1

How to sort characters in a string e.g. "5121" -> "1125" ?

I can do this with code below but it seems too slow:

var nonSortedString = "5121"
var sortedString = String(Array(nonSortedString.characters).sort())
yshilov
  • 774
  • 1
  • 8
  • 11
  • 3
    *"it seems too slow"* – do you have concrete numbers? – Martin R Aug 09 '15 at 12:46
  • If it works and is not a perceptible performance problem it is fine. – zaph Aug 09 '15 at 12:49
  • Well, I have a code in swift and similar code in c++ which is much faster. So I supposed that this conversion string->array->string sows down. in c++ I have std::sort(stringToSort.begin(), stringToSort.end()); – yshilov Aug 09 '15 at 12:52
  • 4
    Concrete speed doesn't really matter, what matters is the complexity (big Oh notation). Also you can't compare string handling between C++ and Swift because Swift has a much more advanced string management structure, with full Unicode support and everything. What happens when there's a compound character in C++? It will look like crap afterwards. Swift though can handle all that, emojis don't get destroyed, everything gets sorted according to human intuition. – Kametrixom Aug 09 '15 at 13:43

1 Answers1

2

The CharacterView handles properly compound characters and provides proper ordering ("eěf" vs. "efě"). If you are ok with the way C++ handles unicode characters, try using one of the other views, like nonSortedString.utf16.sort(). It should give speed similar to C++.

MirekE
  • 11,515
  • 5
  • 35
  • 28
  • 1
    thank you. this helped me to increase the speed in 3.5 times (sorry, I can't vote for the answer because my reputation is low) – yshilov Aug 10 '15 at 19:10
  • In swift this converts to utf16 numbers I think. How do you convert the numbers array back to a string? – C0D3 Dec 01 '17 at 15:49