Instead of two loop functions, I would go with already sorted string in maybe `sprintf()`.