I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

Sort the letters of string in alphabetical order

Sort the letters of string in alphabetical order is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Sorting Algorithm
This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or:

O(n logn) sorts

O(n log2n) sorts
Shell Sort

Write a function/program/subroutine/procedure to sort the characters of a string in lexicographical order.

A character for this purpose should be whatever is natural for your language.

Show the results here on this page.   White-space may be optionally removed.

The case   (uppercase and lowercase)   of any letters should be preserved.

Write the function even if your language has a built-in function for it.

`with Ada.Text_Io;with Ada.Containers.Generic_Array_Sort; procedure Sort_Letters is    function Compare (Left, Right : Character) return Boolean   is (Left < Right);    procedure Sort is new     Ada.Containers.Generic_Array_Sort (Index_Type   => Positive,                                        Element_Type => Character,                                        Array_Type   => String,                                        "<"          => Compare);    use Ada.Text_Io;   B : String := "When Roman engineers built a bridge, they had to stand under it while the first legion marched across. If programmers today worked under similar ground rules, they might well find themselves getting much more interested in Ada!"; begin   Put_Line (B); Sort (B); Put_Line (B);end Sort_Letters;`
Output:
```When Roman engineers built a bridge, they had to stand under it while the first legion marched across. If programmers today worked under similar ground rules, they might well find themselves getting much more interested in Ada!

ALGOL 68

As with the Wren, Go and probably other samples, this defines a bubble sort to sort the text. Non-alphabetic characters are retained.

`BEGIN    # returns s with the characters sorted into lexicographic order          #    OP   LSORT = ( STRING s )STRING:         BEGIN            [ 1 : UPB s[ @ 1 ] ]CHAR c := s[ @ 1 ];            FOR u FROM UPB c - 1 BY -1 TO LWB c            WHILE                BOOL sorted := TRUE;                FOR p FROM LWB c BY 1 TO u DO                    IF c[ p ] > c[ p + 1 ] THEN                        CHAR t := c[ p ];                        c[ p     ] := c[ p + 1 ];                        c[ p + 1 ] := t;                        sorted := FALSE                    FI                OD;                NOT sorted            DO SKIP OD;            c         END; # SORT #    print( ( LSORT "The quick brown fox jumps over the lazy dog, apparently", newline ) )    print( ( LSORT "Now is the time for all good men to come to the aid of their country.", newline ) )END`
Output:
```         ,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy
```

APL

Works with: Dyalog APL
`sort ← ⊂∘⍋⌷⊣`
Output:
```      sort 'Now is the time for all good men to come to the aid of their country.'
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy```

AWK

` # syntax GAWK -f SORT_THE_LETTERS_OF_STRING_IN_ALPHABETICAL_ORDER.AWKBEGIN {    str = "Now is the time for all good men to come to the aid of their country."    printf("old: %s\n",str)    printf("new: %s\n",sortstr(str))    exit(0)}function sortstr(str,  i,j) {    for (i=2; i<=length(str); i++) {      for (j=i; j>1 && substr(str,j-1,1) > substr(str,j,1); j--) {#             < left          > < these are swapped             > < right       >        str = substr(str,1,j-2) substr(str,j,1) substr(str,j-1,1) substr(str,j+1)      }    }    return(str)} `
Output:
```old: Now is the time for all good men to come to the aid of their country.
new:                .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy
```

BCPL

`get "libhdr" let sortchars(str) be\$(  let count = vec 255 and loc = ?    for i=0 to 255 do i!count := 0    for i=1 to str%0 do (str%i)!count := (str%i)!count + 1    loc := 1    for i=0 to 255 until i!count = 0    \$(  str%loc := i        loc := loc + 1        i!count := i!count - 1    \$)\$) let start() be\$(  let string =         "Now is the time for all good men to come to the aid of their country."    writef("%S*N", string)    sortchars(string)    writef("%S*N", string)\$)`
Output:
```Now is the time for all good men to come to the aid of their country.
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy```

C#

Dubbing the following sorting method as "Slacksort". This "Slacksort" method can easily be adapted for reverse sorting, or removing other characters besides space. Not recommended for larger strings though.

`using System; using static System.Console;class Program {  static void Main(string[] args) {    var nl = "\n";    var omit_spaces = true;    var str = "forever ring programming language";    Write( "working..." + nl );    Write( "Sort the letters of string in alphabitical order:" + nl );    Write( "Input: " + str + nl );    Write( "Output: " );    for (var ch = omit_spaces ? 33 : 0; ch < 256; ch++)      foreach (var itm in str)        if (ch == itm) Console.Write(itm);    Write( nl + "done..." );  }}`

Note: this is a bit of a tribute to the original task description and initial Ring entry, so the typographical errors have intentionally not been corrected.

Output:
```working...
Sort the letters of string in alphabitical order:
Input: forever ring programming language
Output: aaaeeefgggggiilmmnnnooprrrrruv
done...
```

F#

` // Alphabetic sort. Nigel Galloway: July 27th., 2021let fG n g=let g=g|>Seq.countBy id|>Map.ofSeq in [for n in n->if Map.containsKey n g then [|for g in 1..g.[n]->n|]|>System.String else ""]|>String.concat ""let English=fG ['a';'A';'b';'B';'c';'C';'d';'D';'e';'E';'f';'F';'g';'G';'h';'H';'i';'I';'j';'J';'k';'K';'l';'L';'m';'M';'n';'N';'o';'O';'p';'P';'q';'Q';'r';'R';'s';'S';'t';'T';'u';'U';'v';'V';'w';'W';'x';'X';'y';'Y';'z';'Z']let Turkish=fG ['a';'A';'b';'B';'c';'C';'ç';'Ç';'d';'D';'e';'E';'f';'F';'g';'G';'ğ';'Ğ';'h';'H';'ı';'I';'i';'İ';'j';'J';'k';'K';'l';'L';'m';'M';'n';'N';'o';'O';'ö';'Ö';'p';'P';'r';'R';'s';'S';'ş';'Ş';'t';'T';'u';'U';'ü';'Ü';'v';'V';'y';'Y';'z';'Z'];let main args=use n=new System.IO.StreamWriter(System.IO.File.Create("out.txt"))              n.WriteLine(English "baNAnaBAnaNA")              n.WriteLine(Turkish (String.filter((<>)' ') "Meseleyi anlamağa başladı"))  `
Output:
```aaaAAAbBnnNN
aaaaaabdeeeğıilllmMnsşy
```

Go

As in the case of the Wren entry, we write a function to bubble sort the characters of a string since this method is not, of course, used in Go's standard 'sort' package.

`package main import (    "fmt"    "strings") func bubbleSort(s string, trim bool) string { // allow optional removal of whitespace    chars := []rune(s)    n := len(chars)    for {        n2 := 0        for i := 1; i < n; i++ {            if chars[i-1] > chars[i] {                tmp := chars[i]                chars[i] = chars[i-1]                chars[i-1] = tmp                n2 = i            }        }        n = n2        if n == 0 {            break        }    }    s = string(chars)    if trim {        s = strings.TrimLeft(s, " \t\r\n")    }    return s} func main() {    ss := []string{        "forever go programming language",        "Now is the time for all good men to come to the aid of their country.",    }    trims := []bool{true, false}    for i, s := range ss {        res := bubbleSort(s, trims[i])        fmt.Printf("Unsorted->%s\n", s)        fmt.Printf("Sorted  ->%s\n\n", res)    }}`
Output:
```Unsorted->forever go programming language
Sorted  ->aaaeeefgggggilmmnnoooprrrruv

Unsorted->Now is the time for all good men to come to the aid of their country.
Sorted  ->               .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy
```

`import Data.List (sort) main :: IO ()main =  print \$    sort      "Is this misspelling of alphabetical as alphabitical a joke ?"`
Output:
`"         ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"`

Or, sketching a rough re-phrase of the question:

`import Data.List (partition) main :: IO ()main =  print \$    qSort      "Is this misspelling of alphabetical as alphabitical a joke ?" qSort :: (Ord a) => [a] -> [a]qSort [] = []qSort (x : xs) = qSort below <> (x : qSort above)  where    (below, above) = partition (<= x) xs`
Output:
`"         ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"`

Or, just constructing a sorted string from the character counts:

`import qualified Data.Map.Strict as M ----------------- MAP OF CHARACTER COUNTS ---------------- charCounts :: String -> M.Map Char IntcharCounts =  foldr (flip (M.insertWith (+)) 1) M.empty  --------------------------- TEST -------------------------main :: IO ()main =  ( print      . (uncurry (flip replicate) =<<)      . M.toList      . charCounts  )    "Was the misspelling of alphabetical as alphabitical a joke ?"`
Output:
`"         ?Waaaaaaaaabbcceeeefghhhiiiiijkllllllmnoopppssssttt"`

jq

Works with: jq

Works with gojq, the Go implementation of jq

An efficient way to sort an arbitrary JSON string is to use the code points of the constituent characters:

` def sort_by_codepoints:  explode | sort | implode;`

For example:

`"Is this misspelling of alphabetical as alphabitical a joke ?"| sort_by_codepoints`
produces
`"         ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"`
An alternative definition using `sort` on the characters themselves:
`def sort_by_characters:  explode | map([.]|implode) | sort | add;`
Are these definitions the same?
`def dingbats:  "✁✂✃✄✆✇✈✉✌✍✎✏✐✑✒✓✔✕✖✗✘✙✚✛✜✝✞✟✠✡✢✣✤✥✦✧✩✪✫✬✭✮✯✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❍❏❐❑❒❖❘❙❚❛❜❝❞❡❢❣❤❥❦❧❶❷❸❹❺❻❼❽❾❿➀➁➂➃➄➅➆➇➈➉➊➋➌➍➎➏➐➑➒➓➔➘➙➚➛➜➝"; "Now is the time for all good men to come to the aid of their country.","Is this misspelling of alphabetical as alphabitical a joke ?",dingbats| (sort_by_codepoints==sort_by_characters) `
produces
```true
true
true
```

Julia

`function mergesort!(array, lt = <, low = 1, high = length(array), tmp=similar(array, 0))    high <= low && return array    middle = low + div(high - low, 2)    (length(tmp) < middle - low + 1) && resize!(tmp, middle - low + 1)     mergesort!(array, lt, low,  middle, tmp)    mergesort!(array, lt, middle + 1, high, tmp)     i, j = 1, low    while j <= middle        tmp[i] = array[j]        i += 1        j += 1    end     i, k = 1, low    while k < j <= high        if lt(array[j], tmp[i])            array[k] = array[j]            j += 1        else            array[k] = tmp[i]            i += 1        end        k += 1    end     while k < j        array[k] = tmp[i]        k += 1        i += 1    end    return arrayend mergesort(str::String) = String(mergesort!(collect(str))) function testmergesort(s::String, stripws= true)    println("Unsorted -> ", s)    println("Sorted   -> ", stripws ? strip(mergesort(s)) : mergesort(s))end testmergesort("forever julia programming language")testmergesort("Now is the time for all good men to come to the aid of their country.", false) `
Output:
```Unsorted -> forever julia programming language
Sorted   -> aaaaeeefggggiijllmmnnooprrrruuv
Unsorted -> Now is the time for all good men to come to the aid of their country.
Sorted   ->                .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy
```

case insensitive quicksort

`function qsort(array)    length(array) < 2 && return array    mid, left, right  = first(array), eltype(array)[], eltype(array)[]    for elem in @view array[begin+1:end]        push!(lowercase(elem) < lowercase(mid) ? left : right, elem)    end    return vcat(qsort(left), mid, qsort(right))end qsort(str::String) = str |> collect |> qsort |> String function testqsort(s::String, stripws= true)    println("Unsorted -> ", s)    println("Sorted   -> ", stripws ? strip(qsort(s)) : qsort(s))end testqsort("forever julia programming language")testqsort("Now is the time for all good men to come to the aid of their country.") `
Output:
```Unsorted -> forever julia programming language
Sorted   -> aaaaeeefggggiijllmmnnooprrrruuv
Unsorted -> Now is the time for all good men to come to the aid of their country.
Sorted   ->                .aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy
```

Mathematica/Wolfram Language

`sortstring = Characters /* LexicographicSort /* StringJoin;sortstring["Now is the time for all good men to come to the aid of their country."]`
Output:
`".               aaccddeeeeeeffghhhiiiillmmmnnNooooooooorrrstttttttuwy"`

Nim

`import strutils, tables func sorted(text: string; omitSpaces = false): string =  let count = text.toCountTable()  for c in '\0'..'\255':    if c == ' ' and omitSpaces: continue    result.add repeat(c, count[c]) echo sorted("The quick brown fox jumps over the lazy dog, apparently", false)echo sorted("Now is the time for all good men to come to the aid of their country.", true)`
Output:
```         ,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy```

Perl

`#!/usr/bin/perl -l use strict; # https://rosettacode.org/wiki/Sort_the_letters_of_string_in_alphabitical_orderuse warnings; my @lines = split /\n/, <<END;The quick brown fox jumps over the lazy dog, apparentlyNow is the time for all good men to come to the aid of their country.END for ( @lines, 'dcba', 'sort this string' )  {  print "\n\$_";  print builtinsort(\$_); #     using built in sort  print sortstring(\$_);  # not using built in sort  print inplace(\$_);     # not using built in sort  } sub builtinsort  {  return join '', sort split //, shift;  } sub sortstring # IBM card sorters forever !! (distribution sort)  {  my @chars;  \$chars[ord] .= \$_ for split //, shift;  no warnings; # hehehe  return join '', @chars;  } sub inplace # just swap any adjacent pair not in order until none found  {  local \$_ = shift;  1 while s/(.)(.)(??{\$1 le \$2 && '(*FAIL)'})/\$2\$1/g;  return \$_;  }`
Output:
```The quick brown fox jumps over the lazy dog, apparently
,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz
,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz
,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz

Now is the time for all good men to come to the aid of their country.
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy

dcba
abcd
abcd
abcd

sort this string
```

Phix

Not sure this algorithm actually has a name, but it certainly ain't the fastest, though it possibly is just about the shortest...
(If pressed I would dub this "Unoptimised bubble sort without the swapped flag")

```with javascript_semantics
function string_sort(string s)
integer temp
for n=1 to length(s)-1 do
for m=n+1 to length(s) do
if s[n]>s[m] then
temp = s[n]
s[n] = s[m]
s[m] = temp
end if
end for
end for
return s
end function
string s = "Now is the time for all good men to come to the aid of their country."
printf(1,"Original:\"%s\",\n  Sorted:\"%s\"\n Builtin:\"%s\"\n",{s,string_sort(s),sort(s)})
```
Output:
```Original:"Now is the time for all good men to come to the aid of their country.",
Sorted:"               .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy"
Builtin:"               .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy"
```

case insensitive

You can make this case insensitive by applying lower() on each internal comparison, whereas with the builtins that is done (more efficiently) by extracting a custom tagsort.
(Just to keep you on your toes I've also replaced the algorithm with a fractionaly saner insertion sort, and just to be awkward I've added the baNAnaBAnaNA case.)

```with javascript_semantics
function string_sort(string s)
for i=2 to length(s) do
integer j = i, sj = s[j]
while j>=2 and lower(sj)<lower(s[j-1]) do
s[j] = s[j-1]
j -= 1
end while
s[j] = sj
end for
return s
end function

procedure test(string s)
string cia = extract(s,custom_sort(lower(s),tagset(length(s))))
printf(1,"Original:\"%s\",\n  Sorted:\"%s\"\n Builtin:\"%s\"\n",{s,string_sort(s),cia})
end procedure
test("Now is the time for all good men to come to the aid of their country.")
test("baNAnaBAnaNA") -- (just to be awkward)
```
Output:
```Original:"Now is the time for all good men to come to the aid of their country.",
Sorted:"               .aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy"
Builtin:"               .aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy"
Original:"baNAnaBAnaNA",
Sorted:"aAaAaAbBNnnN"
Builtin:"aAaAaAbBNnnN"
```

Should you want/prefer the output of baNAnaBAnaNA to be AAAaaaBaNNnn, change the test (leaving the builtin/cia as an exercise) to

```        while j>=2 and (lower(sj)<lower(s[j-1]) or sj=s[j-1]-32) do
```

Or of course for aaaAAAbBnnNN use

```        while j>=2 and (lower(sj)<lower(s[j-1]) or sj-32=s[j-1]) do
```

Python

`'''Sorted string''' from functools import reduce  # qSort :: [a] -> [a]def qSort(xs):    '''Sorted elements of the list xs, where the values       of xs are assumed to be of some orderable type.    '''    if xs:        h = xs[0]        below, above = partition(            lambda v: v <= h        )(xs[1:])         return qSort(below) + [h] + qSort(above)    else:        return []  # ------------------------- TEST -------------------------def main():    '''A character-sorted version of a test string    '''    print(quoted('"')(        ''.join(qSort(list(            "Is this misspelling of alphabetical as alphabitical a joke ?"        )))    ))  # ----------------------- GENERIC ------------------------ # partition :: (a -> Bool) -> [a] -> ([a], [a])def partition(p):    '''The pair of lists of those elements in xs       which respectively do, and don't       satisfy the predicate p.    '''    def go(a, x):        ts, fs = a        return (ts + [x], fs) if p(x) else (ts, fs + [x])    return lambda xs: reduce(go, xs, ([], []))  # quoted :: Char -> String -> Stringdef quoted(c):    '''A string flanked on both sides       by a specified quote character.    '''    return lambda s: c + s + c  # MAIN ---if __name__ == '__main__':    main()`
Output:
`"         ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"`

Raku

Semi-realistic version

`sub sort_within_string ( \$_ is copy ) {    constant @lexographic_order = sort *.fc, map &chr, 1..255;     return join '', gather for @lexographic_order -> \$l {        my \$count = s:g/\$l//;        take \$l x \$count;        LAST { warn "Original string had non-ASCII chars: {.raku}" if .chars }    }}say trim .&sort_within_string for q:to/END/.lines;The quick brown fox jumps over the lazy dog, apparentlyNow is the time for all good men to come to the aid of their country.END `
Output:
```,aaabcdeeeefghhijkllmnnoooopppqrrrsTttuuvwxyyz
.aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy
```

Following the actual task title / description

Following a strict interpretation of the actual task title and description.

• Sorts letters. Only letters. Into alphabetical order. Regardless of case. EVERYTHING else is ignored / pushed to the end of the "sorted" string. Not ASCII order. Not EBCDIC order. Only alphabetical order. If it ain't in the alphabet, it ain't sorted.
• Sorts letters of the string two characters at a time as a string. No breaking up the string into a list or array, sorting that then joining back together; or picking characters out of a string to generate a new string. Sorts a string, as a string, in place.

Sorted output is wrapped in double guillemots to make it easier to see where it starts and ends.

`sub moronic-sort (\$string is copy) {    my \$chars = \$string.chars;    loop {        for ^\$chars {            if (\$string.substr(\$_, 1).fc gt \$string.substr(\$_ + 1, 1).fc and \$string.substr(\$_ + 1, 1) ~~ /<:L>/)               or \$string.substr(\$_, 1) ~~ /<:!L>/ {                \$string = \$string.substr(0, \$_) ~ \$string.substr(\$_ , 2).flip ~ \$string.substr(\$_ + 2 min \$chars);            }        }        last if \$++ >= \$chars;    }    \$string} sub wrap (\$whatever) { '»»' ~ \$whatever ~ '««' }  # Test sort the exact string as specified in the task title.say "moronic-sort 'string'\n" ~ wrap moronic-sort 'string';  # Other tests demonstrating the extent of the stupidity of this task.say "\nLonger test sentence\n" ~ wrap moronic-sort q[This is a moronic sort. It's only concerned with sorting letters, so everything else is pretty much ignored / pushed to the end. It also doesn't much care about letter case, so there is no upper / lower case differentiation.];  say "\nExtended test string:\n" ~ my \$test = (32..126)».chr.pick(*).join;say wrap moronic-sort \$test;`
Output:
```moronic-sort 'string'
»»ginrst««

Longer test sentence
»»aaaaaaabccccccccddddddeeeeeeeeeeeeeeeeeeeeeeeeeffggghhhhhhhhiiiIiiiiiIiiiillllllmmmnnnnnnnnnnnnoooooooooooooooopppprrrrrrrrrrrrrrssssssssssssssssTtttttttttttttttttttuuuuuvwwyyy    ,      /   .    . '     ,        /    .   ' ««

Extended test string:
!kjyxAa+,LGh_8?3lXEwW-D]Ku|SY[@VF\.op{=q>MT 1tJ/\$nN(Z*%&9^v57")`PCiOHQe'RUb<gs;6}#cfmrzd42B~0I:

REXX

For REXX, it is normally faster to convert a string of characters to a one─character array of characters,
sort the array,   and then convert the array back to a (simple) string.

A simple bubble sort is used for this example.

The particular string used is from a typing drill devised by Charles E. Weller in the early 20th century.

`/*REXX program sorts an array  (of any kind of items)  using the  bubble─sort algorithm.*/parse arg y                                      /*generate the array elements  (items).*/if y=''  then y= "Now is the time for all good men to come to the aid of their country."             say 'before sort: ───►'y"◄───"      /*show the  before string of characters*/call [email protected]    y                                  /*convert a string into an array  (@.) */call bSort    #                                  /*invoke the bubble sort  with # items.*/call makeS                                       /*convert an array (@.) into a string. */             say ' after sort: ───►'\$"◄───"      /*show the  before string of characters*/exit 0                                           /*stick a fork in it,  we're all done. *//*──────────────────────────────────────────────────────────────────────────────────────*/bSort: procedure expose @.;  parse arg n         /*N: is the number of @ array elements.*/         do m=n-1  by -1  until ok;        ok= 1 /*keep sorting the  @ array until done.*/           do j=1  for m;  k= j+1;  if @.j<[email protected].k  then iterate      /*elements in order? */           _= @.j;  @.j= @.k;  @.k= _;     ok= 0 /*swap two elements;  flag as not done.*/           end   /*j*/         end     /*m*/;               return/*──────────────────────────────────────────────────────────────────────────────────────*/[email protected]: parse arg z;  #= length(z);    do j=1  for #;  @.j= substr(z, j, 1);  end;   returnmakeS: parse arg a;  \$=;              do j=1  for #;  \$= \$  ||  @.j;         end;   return`
output   when using the default input:
```before sort: ───►Now is the time for all good men to come to the aid of their country.◄───
after sort: ───►               .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy◄───
```

Ring

` see "working..." + nlsee "Sort the letters of string in alphabitical order:" + nlstr = "forever ring programming language"see "Input: " + str + nl for n = 1 to len(str)-1    for m = n+1 to len(str)        if ascii(str[n]) > ascii(str[m])           temp = str[n]           str[n] = str[m]           str[m] = temp        ok    nextnext str = substr(str," ","")see "Output: " + str + nlsee "done..." + nl `
Output:
```working...
Sort the letters of string in alphabitical order:
Input: forever ring programming language
Output: aaaeeefgggggiilmmnnnooprrrrruv
done...
```

Wren

Well, we'll write a function for a bubble sort which we don't have in Wren-sort because it's normally much slower than the other methods. However, it's fast enough here.

`var bubbleSort = Fn.new { |s, trim|  // allow optional removal of whitespace    var chars = s.toList    var n = chars.count    while (true) {        var n2 = 0        for (i in 1...n) {            if (chars[i - 1].codePoints[0] > chars[i].codePoints[0]) {                chars.swap(i, i - 1)                n2 = i            }        }        n = n2        if (n == 0) break    }    s = chars.join()    return trim ? s.trim() : s} var strs = [    ["forever wren programming language", true],    ["Now is the time for all good men to come to the aid of their country.", false]]for (str in strs) {    System.print(["Unsorted->" + str[0], "Sorted  ->" + bubbleSort.call(str[0], str[1])].join("\n"))    System.print()}`
Output:
```Unsorted->forever wren programming language
Sorted  ->aaaeeeefggggilmmnnnooprrrrruvw

Unsorted->Now is the time for all good men to come to the aid of their country.
Sorted  ->               .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy
```

XPL0

`string  0;              \use zero-terminated strings func    StrLen(Str);    \Return number of characters in an ASCIIZ stringchar    Str;int     I;for I:= 0 to -1>>1 do        if Str(I) = 0 then return I; func Sort(Str);         \Bubble sort string Strchar Str;int  J, I, T;[for J:= StrLen(Str)-1 downto 0 do    for I:= 0 to J-1 do        if Str(I) > Str(I+1) then            [T:= Str(I);  Str(I):= Str(I+1);  Str(I+1):= T];return Str;]; [Text(0, Sort("The quick brown fox jumps over the lazy dog."));CrLf(0);Text(0, Sort("Pack my box with five dozen liquor jugs."));CrLf(0);]`
Output:
```        .Tabcdeeefghhijklmnoooopqrrstuuvwxyz
.Pabcdeefghiiijklmnoooqrstuuvwxyz
```