Sort the letters of string in alphabetical order: Difference between revisions

From Rosetta Code
Content added Content deleted
(Add C++)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(30 intermediate revisions by 15 users not shown)
Line 16: Line 16:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>F sorted_str(s)
<syntaxhighlight lang="11l">F sorted_str(s)
DefaultDict[Char, Int] d
DefaultDict[Char, Int] d
L(c) s
L(c) s
Line 26: Line 26:


print(sorted_str(‘The quick brown fox jumps over the lazy dog, apparently’))
print(sorted_str(‘The quick brown fox jumps over the lazy dog, apparently’))
print(sorted_str(‘Is this misspelling of alphabetical as alphabitical a joke ?’))</lang>
print(sorted_str(‘Is this misspelling of alphabetical as alphabitical a joke ?’))</syntaxhighlight>


{{out}}
{{out}}
Line 36: Line 36:
=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang="action!">INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit


PROC Test(CHAR ARRAY s)
PROC Test(CHAR ARRAY s)
Line 48: Line 48:
Test("The quick brown fox jumps over the lazy dog, apparently")
Test("The quick brown fox jumps over the lazy dog, apparently")
Test("Now is the time for all good men to come to the aid of their country.")
Test("Now is the time for all good men to come to the aid of their country.")
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sort_the_letters_of_string_in_alphabetical_order.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sort_the_letters_of_string_in_alphabetical_order.png Screenshot from Atari 8-bit computer]
Line 66: Line 66:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Containers.Generic_Array_Sort;
with Ada.Containers.Generic_Array_Sort;


Line 85: Line 85:
begin
begin
Put_Line (B); Sort (B); Put_Line (B);
Put_Line (B); Sort (B); Put_Line (B);
end Sort_Letters;</lang>
end Sort_Letters;</syntaxhighlight>
{{out}}
{{out}}
<pre>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!
<pre>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!
Line 92: Line 92:
=={{header|ALGOL 68}}==
=={{header|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.
As with the Wren, Go and probably other samples, this defines a bubble sort to sort the text. Non-alphabetic characters are retained.
<lang algol68>BEGIN
<syntaxhighlight lang="algol68">BEGIN
# returns s with the characters sorted into lexicographic order #
# returns s with the characters sorted into lexicographic order #
OP LSORT = ( STRING s )STRING:
OP LSORT = ( STRING s )STRING:
Line 114: Line 114:
print( ( LSORT "The quick brown fox jumps over the lazy dog, apparently", newline ) )
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 ) )
print( ( LSORT "Now is the time for all good men to come to the aid of their country.", newline ) )
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 120: Line 120:
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy
</pre>
</pre>

=={{header|ALGOL W}}==
Sorts the letters, leaving the non-letters unsorted.
<syntaxhighlight lang="algolw">
begin
% returns s with the letters sorted %
% as Algol W doesn't have variable length strings, %
% the number of characters to sort must be specified %
% in len %
string(256) procedure lSort( string(256) value s; integer value len ) ;
begin
string(256) letters, sortedS;
integer lLen, lPos, u;
sortedS := s;
% get the letters %
letters := "";
lLen := -1;
for i := 0 until len - 1 do begin
string(1) c;
c := s( i // 1 );
if ( c >= "a" and c <= "z" ) or ( c >= "A" and c <= "Z" ) then begin
lLen := lLen + 1;
letters( lLen // 1 ) := c
end if_we_have_a_letter
end for_i ;
% bubble sort the letters %
u := lLen;
while begin
logical sorted;
sorted := true;
u := u - 1;
for p := 0 until u do begin
string(1) c, d;
c := letters( p // 1 );
d := letters( p + 1 // 1 );
if c > d then begin
letters( p // 1 ) := d;
letters( p + 1 // 1 ) := c;
sorted := false
end if_c_gt_d
end for_p ;
not sorted
end do begin end;
% put the sorted letters into the result string %
lPos := -1;
for i := 0 until len - 1 do begin
string(1) c;
c := s( i // 1 );
if ( c >= "a" and c <= "z" ) or ( c >= "A" and c <= "Z" ) then begin
lpos := lPos + 1;
sortedS( i // 1 ) := letters( lPos // 1 )
end if_we_have_a_letter
end for_i ;
sortedS
end lSort ;
% prints the first len characters of s %
procedure writeOnString( string(256) value s; integer value len ) ;
for i := 0 until len - 1 do writeon( s_w := 0, s( i // 1 ) );
% tests the lSort procedure %
procedure testSort( string(256) value s; integer value len ) ;
begin
writeon( s_w := 0, " [" );writeOnString( s, len ); writeon( "]" );write();
writeon( s_w := 0, " -> [" );writeOnString( lSort( s, len ), len ); writeon( "]" );write()
end testSort ;

testSort( "The quick brown fox jumps over the lazy dog, apparently", 55 );
testSort( "Now is the time for all good men to come to the aid of their country.", 69 );
testSort( "Stop! In the name of Wuv!", 25 )
end.
</syntaxhighlight>
{{out}}
<pre>
[The quick brown fox jumps over the lazy dog, apparently]
-> [Taa abcde eeefg hhi jkllm nnoo oop ppqr rrs, ttuuvwxyyz]
[Now is the time for all good men to come to the aid of their country.]
-> [Naa cc dde eeee eff ghh hiii ill mm mnno oo ooo ooo rr rsttt ttttuwy.]
[Stop! In the name of Wuv!]
-> [ISWa! ee fhm nnoo pt tuv!]</pre>


=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}
<lang APL>sort ← ⊂∘⍋⌷⊣</lang>
<syntaxhighlight lang="apl">sort ← ⊂∘⍋⌷⊣</syntaxhighlight>
{{out}}
{{out}}
<pre> sort 'Now is the time for all good men to come to the aid of their country.'
<pre> sort 'Now is the time for all good men to come to the aid of their country.'
Line 129: Line 207:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>sortLetters(str, RemoveSpace := 1){
<syntaxhighlight lang="autohotkey">sortLetters(str, RemoveSpace := 1){
oChar := []
oChar := []
for i, v in StrSplit(str)
for i, v in StrSplit(str)
Line 141: Line 219:
result .= letter
result .= letter
return result
return result
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>str1 := "The quick brown fox jumps over the lazy dog, apparently"
Examples:<syntaxhighlight lang="autohotkey">str1 := "The quick brown fox jumps over the lazy dog, apparently"
str2 := "Now is the time for all good men to come to the aid of their country."
str2 := "Now is the time for all good men to come to the aid of their country."


MsgBox, 262144, , % result := str1 " ->`n" sortLetters(str1)
MsgBox, 262144, , % result := str1 " ->`n" sortLetters(str1)
. "`n`n" str2 " ->`n" sortLetters(str2, 0)</lang>
. "`n`n" str2 " ->`n" sortLetters(str2, 0)</syntaxhighlight>
{{out}}
{{out}}
<pre>The quick brown fox jumps over the lazy dog, apparently ->
<pre>The quick brown fox jumps over the lazy dog, apparently ->
Line 155: Line 233:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax GAWK -f SORT_THE_LETTERS_OF_STRING_IN_ALPHABETICAL_ORDER.AWK
# syntax GAWK -f SORT_THE_LETTERS_OF_STRING_IN_ALPHABETICAL_ORDER.AWK
BEGIN {
BEGIN {
Line 172: Line 250:
return(str)
return(str)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 180: Line 258:


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


let sortchars(str) be
let sortchars(str) be
Line 200: Line 278:
sortchars(string)
sortchars(string)
writef("%S*N", string)
writef("%S*N", string)
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>Now is the time for all good men to come to the aid of their country.
<pre>Now is the time for all good men to come to the aid of their country.
Line 206: Line 284:


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


/* Sort a character string in place */
/* Sort a character string in place */
Line 224: Line 302:
puts(s);
puts(s);
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Now is the time for all good men to come to the aid of their country.
<pre>Now is the time for all good men to come to the aid of their country.
Line 230: Line 308:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iostream>


Line 241: Line 319:
std::cout << s << std::endl;
std::cout << s << std::endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Now is the time for all good men to come to the aid of our country.
<pre>Now is the time for all good men to come to the aid of our country.
Line 248: Line 326:
=={{header|C#|CSharp}}==
=={{header|C#|CSharp}}==
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.
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.
<lang csharp>using System; using static System.Console;
<syntaxhighlight lang="csharp">using System; using static System.Console;
class Program {
class Program {
static void Main(string[] args) {
static void Main(string[] args) {
Line 254: Line 332:
var omit_spaces = true;
var omit_spaces = true;
var str = "forever ring programming language";
var str = "forever ring programming language";
Console.Write( "working..." + nl );
Write( "working..." + nl );
Console.Write( "Sort the letters of string in alphabitical order:" + nl );
Write( "Sort the letters of string in alphabitical order:" + nl );
Console.Write( "Input: " + str + nl );
Write( "Input: " + str + nl );
Console.Write( "Output: " );
Write( "Output: " );
for (var ch = omit_spaces ? 33 : 0; ch < 256; ch++)
for (var ch = omit_spaces ? 33 : 0; ch < 256; ch++)
foreach (var itm in str)
foreach (var itm in str)
if (ch == itm) Console.Write(itm);
if (ch == itm) Console.Write(itm);
Console.Write( nl + "done..." );
Write( nl + "done..." );
}
}
}</lang>
}</syntaxhighlight>
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.
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.
{{out}}
{{out}}
Line 275: Line 353:


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>% Unicode is explicitly not supported, the standard says
<syntaxhighlight lang="clu">% Unicode is explicitly not supported, the standard says
% that "every implementation must provide at least 128,
% that "every implementation must provide at least 128,
% but no more than 512, characters".
% but no more than 512, characters".
Line 303: Line 381:
stream$putl(po, str)
stream$putl(po, str)
stream$putl(po, sort_string(str))
stream$putl(po, sort_string(str))
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
<pre>Now is the time for all good men to come to the aid of their country.
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy</pre>

=={{header|Comal}}==
<syntaxhighlight lang="comal">0010 PROC strsort(REF s$) CLOSED
0020 DIM count#(0:255)
0030 FOR i#:=1 TO LEN(s$) DO count#(ORD(s$(i#))):+1
0040 i#:=1
0050 FOR j#:=0 TO 255 DO
0060 IF count#(j#)>0 THEN
0070 s$(i#:i#+count#(j#)-1):=CHR$(j#)*count#(j#)
0080 i#:+count#(j#)
0090 ENDIF
0100 ENDFOR j#
0110 ENDPROC strsort
0120 //
0130 test$:="Now is the time for all good men "
0140 test$:+"to come to the aid of their country."
0150 PRINT test$
0160 strsort(test$)
0170 PRINT test$
0180 END</syntaxhighlight>
{{out}}
{{out}}
<pre>Now is the time for all good men to come to the aid of their country.
<pre>Now is the time for all good men to come to the aid of their country.
Line 309: Line 410:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>
<syntaxhighlight lang="lisp">
(sort "Now is the time for all good men to come to the aid of their country." #'char<=)
(sort "Now is the time for all good men to come to the aid of their country." #'char<=)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
" .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy"
" .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy"
</pre>


=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
Uses Delphi TStringList component to do most of the heavy lifting. The TStringList is designed to hold and maniputlate strings. In the strings are one character long so it sorts characters from the strings.

<syntaxhighlight lang="Delphi">
function SortStringLetters(S: string): string;
{Extract letters from string and sort them}
{Uses string list component to hold and sort chars}
var SL: TStringList;
var I: integer;
begin
SL:=TStringList.Create;
try
for I:=1 to Length(S) do SL.Add(S[I]);
SL.Sort;
SetLength(Result,SL.Count);
for I:=0 to SL.Count-1 do
Result[I+1]:=SL[I][1];
finally SL.Free; end;
end;

const S1 = 'Now is the time for all good men to come to the aid of the party.';
const S2 = 'See the quick brown fox jump over the lazy dog.';

procedure ShowSortedLetters(Memo: TMemo);
var S: string;
begin
Memo.Lines.Add('Unsorted = '+S1);
Memo.Lines.Add('Sorted = '+SortStringLetters(S1));
Memo.Lines.Add('Unsorted = '+S2);
Memo.Lines.Add('Sorted = '+SortStringLetters(S2));
end;

</syntaxhighlight>
{{out}}
<pre>
Unsorted = Now is the time for all good men to come to the aid of the party.
Sorted = .aaacddeeeeeeffghhhiiillmmmNnooooooooprrstttttttwy
Unsorted = See the quick brown fox jump over the lazy dog.
Sorted = .abcdeeeeefghhijklmnoooopqrrSttuuvwxyz

Elapsed Time: 5.996 ms.

</pre>
</pre>


=={{header|Draco}}==
=={{header|Draco}}==
<lang draco>/* Sort a string in place, using a counting sort. */
<syntaxhighlight lang="draco">/* Sort a string in place, using a counting sort. */
proc nonrec stringsort(*char str) void:
proc nonrec stringsort(*char str) void:
[256] word counts;
[256] word counts;
Line 353: Line 501:
stringsort(s);
stringsort(s);
writeln(s)
writeln(s)
corp</lang>
corp</syntaxhighlight>
{{out}}
{{out}}
<pre>Now is the time for all good men to come to the aid of their country.
<pre>Now is the time for all good men to come to the aid of their country.
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy</pre>
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy</pre>

=={{header|Eiffel}}==

[https://github.com/ljr1981/rosettacode_answers/blob/main/src/sort_string_letters/sort_string_letters.e Example Code]

<syntaxhighlight lang="eiffel">
class
SORT_STRING_LETTERS

feature -- Basic Ops

sort_string (s: STRING): STRING
-- Perform `sort_string' on `s' such that
-- each letter is in ascending alphabetical order.
note
deviation: "[
This Eiffel example deviates from the task requirement for this
Rosetta Code task in that we reuse Eiffel Base library code for
the {SORTED_TWO_WAY_LIST [G]}. We do this for two very good reasons:
1. Reuse is king. Never code what is already coded and tested.
2. The library code is readily available for examination
(i.e. the library code is not hidden and unaccessible).
Based on #1 and #2 above, examine the code in: {SORTED_TWO_WAY_LIST}.make_from_iterable
Specifically, look at the `extend' routine and the routines it calls (i.e. `search_after',
`put_left', and `back'). These routines will tell you the story of how sorting can
be coded in Eiffel. There is no need to rehash that code here.
]"
local
l_list: SORTED_TWO_WAY_LIST [CHARACTER]
do
create l_list.make_from_iterable (s) -- Add & Auto-sort string by chars
create Result.make_empty -- Create the Result STRING
⟳ c:l_list ¦ Result.append_character (c) ⟲ -- Populate it with the sorted chars
Result.adjust -- Remove the leading white space
ensure
no_spaces: ∀ c:Result ¦ c /= ' ' -- All spaces removed.
has_all: ∀ c:Result ¦ s.has (c) -- All non-space chars present.
valid_count: Result.count =
(s.count - s.occurrences (' ')) -- Every character (even repeating).
end

end
</syntaxhighlight>

Notice the use of Design-by-Contract in the "ensure" at the end of `sort_string'. At testing runtime, we want the routine itself to ensure that the resulting string has no space character and that every character that we passed in the `s' argument is represented in the result string. We even go so far as to ensure that repeating characters are all represented. We could go further, but we felt these contracts
were sufficient to get the point of Design-by-Contract across to you as the reader.

Also note the unicode characters of ⟳ .. ⟲ and ∀. These are called across-loops and we have used the "symbolic form" of them. The first one simply says, "Across all items in l_list as c, perform the code between the ¦ and closing ⟲. In the case of the ∀, this is a loop stating that every member of the Result STRING must hold true for the Boolean expression. For example, in the "no_spaces" contract, we are saying that each character "c" must not be equal to a space (e.g. ' ').

And the Test Code to operate it.

[https://github.com/ljr1981/rosettacode_answers/blob/main/testing/rc_sort_string_letters/rc_sort_string_letters_test_set.e Test Code]

<syntaxhighlight lang="eiffel">
class
RC_SORT_STRING_LETTERS_TEST_SET

inherit
TEST_SET_SUPPORT

feature -- Test routines

rc_sort_string_letters_test
-- Test {SORT_STRING_LETTERS}.
note
testing:
"covers/{SORT_STRING_LETTERS}",
"execution/isolated",
"execution/serial"
do
assert_strings_equal ("sorted", now_is_string, item.sort_string ("Now is the time for all good men to come to the aid of their country."))
end

feature {NONE} -- Test Support

now_is_string: STRING = "[
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy
]"

item: SORT_STRING_LETTERS
-- An `item' for testing.
once
create Result
end

end
</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
// Alphabetic sort. Nigel Galloway: July 27th., 2021
// Alphabetic sort. Nigel Galloway: July 27th., 2021
let 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 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 ""
Line 368: Line 605:
n.WriteLine(Turkish (String.filter((<>)' ') "Meseleyi anlamağa başladı"))
n.WriteLine(Turkish (String.filter((<>)' ') "Meseleyi anlamağa başladı"))


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 376: Line 613:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>
<syntaxhighlight lang="freebasic">
function value( s as string ) as integer
function value( s as string ) as integer
'maps a=A=0, b=B=1, etc
'maps a=A=0, b=B=1, etc
Line 401: Line 638:


sortstr( example, sorted )
sortstr( example, sorted )
print sorted</lang>
print sorted</syntaxhighlight>
{{out}}<pre>aaaaaaaaaabbccddddddddeeeeeeeeefgggghiiIiiiiklmmmnnnnnnnnnOooooopprrrrrrrstttuuuvwwyyyy</pre>
{{out}}<pre>aaaaaaaaaabbccddddddddeeeeeeeeefgggghiiIiiiiklmmmnnnnnnnnnOooooopprrrrrrrstttuuuvwwyyyy</pre>


=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn AlphabetizeString( string as CFStringRef, deleteSpaces as BOOL ) as CFStringRef
NSUInteger i, count
CFStringRef tempStr, alphaStr = NULL
CFArrayRef array
if deleteSpaces then tempStr = fn StringByReplacingOccurrencesOfString( string, @" ", @"" ) else tempStr = string
count = fn StringLength( tempStr )
CFMutableArrayRef mutArr = fn MutableArrayWithCapacity(count)
for i = 0 to count -1
CFStringRef chr = fn StringWithFormat( @"%C", fn StringCharacterAtIndex( tempStr, i ) )
MutableArrayInsertObjectAtIndex( mutArr, chr, i )
next
array = fn ArraySortedArrayUsingSelector( mutArr, @"localizedCaseInsensitiveCompare:" )
alphaStr = fn ArrayComponentsJoinedByString( array, @"" )
end fn = alphaStr

CFStringRef testStr

testStr = @"The quick brown fox jumped over the lazy dog's back."
print testStr
print "String alphabetized with spaces included:"
print fn AlphabetizeString( testStr, NO )
print
testStr = @"Now is the time for all good men to come to the aid of their country."
print testStr
print "String alphabetized with spaces deleted:"
print fn AlphabetizeString( testStr, YES )

HandleEvents
</syntaxhighlight>
{{output}}
<pre>
The quick brown fox jumped over the lazy dog's back.
String alphabetized with spaces included:
.'aabbccddeeeefghhijkklmnoooopqrrsTtuuvwxyz

Now is the time for all good men to come to the aid of their country.
String alphabetized with spaces deleted:
.aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy
</pre>



=={{header|Go}}==
=={{header|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.
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.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 449: Line 732:
fmt.Printf("Sorted ->%s\n\n", res)
fmt.Printf("Sorted ->%s\n\n", res)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 461: Line 744:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Data.List (sort)
<syntaxhighlight lang="haskell">import Data.List (sort)


main :: IO ()
main :: IO ()
Line 467: Line 750:
print $
print $
sort
sort
"Is this misspelling of alphabetical as alphabitical a joke ?"</lang>
"Is this misspelling of alphabetical as alphabitical a joke ?"</syntaxhighlight>
{{Out}}
{{Out}}
<pre>" ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"</pre>
<pre>" ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"</pre>
Line 473: Line 756:
Or, sketching a rough re-phrase of the question:
Or, sketching a rough re-phrase of the question:


<lang haskell>import Data.List (partition)
<syntaxhighlight lang="haskell">import Data.List (partition)


main :: IO ()
main :: IO ()
Line 485: Line 768:
qSort (x : xs) = qSort below <> (x : qSort above)
qSort (x : xs) = qSort below <> (x : qSort above)
where
where
(below, above) = partition (<= x) xs</lang>
(below, above) = partition (<= x) xs</syntaxhighlight>
{{Out}}
{{Out}}
<pre>" ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"</pre>
<pre>" ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"</pre>
Line 492: Line 775:
Or, just constructing a sorted string from the character counts:
Or, just constructing a sorted string from the character counts:


<lang haskell>import qualified Data.Map.Strict as M
<syntaxhighlight lang="haskell">import qualified Data.Map.Strict as M


----------------- MAP OF CHARACTER COUNTS ----------------
----------------- MAP OF CHARACTER COUNTS ----------------
Line 509: Line 792:
. charCounts
. charCounts
)
)
"Was the misspelling of alphabetical as alphabitical a joke ?"</lang>
"Was the misspelling of alphabetical as alphabitical a joke ?"</syntaxhighlight>
{{Out}}
{{Out}}
<pre>" ?Waaaaaaaaabbcceeeefghhhiiiiijkllllllmnoopppssssttt"</pre>
<pre>" ?Waaaaaaaaabbcceeeefghhhiiiiijkllllllmnoopppssssttt"</pre>

=={{header|J}}==
J's builtin is 'grade' and sort is a derived function whose domain includes sequences of characters, so:<syntaxhighlight lang="j"> text0=: 'This is a test'
text1=: 'The sentence "The quick brown fox jumps over the lazy dog" uses every letter in the alphabet.'
/:~ text0
Taehiissstt
/:~ text1
"".TTaaabbccdeeeeeeeeeeeeeefghhhhhiijklllmnnnnooooppqrrrrssssttttttuuuvvwxyyz</syntaxhighlight>

However, sorting characters is easy to implement using [[wp:Bucket_sort|bucket sort]]:<syntaxhighlight lang="j"> {{a.#~<:#/.~a.,y}} text0
Taehiissstt
{{a.#~<:#/.~a.,y}} text1
"".TTaaabbccdeeeeeeeeeeeeeefghhhhhiijklllmnnnnooooppqrrrrssssttttttuuuvvwxyyz</syntaxhighlight>

(Since there's no comparison between pairs in bucket sort, performance here is O(n) rather than O(n log n).)


=={{header|jq}}==
=={{header|jq}}==
Line 518: Line 816:


An efficient way to sort an arbitrary JSON string is to use the code points of the constituent characters:
An efficient way to sort an arbitrary JSON string is to use the code points of the constituent characters:
<syntaxhighlight lang="jq">
<lang jq>
def sort_by_codepoints:
def sort_by_codepoints:
explode | sort | implode;</lang>
explode | sort | implode;</syntaxhighlight>


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


Line 533: Line 831:
dingbats
dingbats
| (sort_by_codepoints==sort_by_characters)
| (sort_by_codepoints==sort_by_characters)
</lang>produces
</syntaxhighlight>produces
<pre>
<pre>
true
true
Line 541: Line 839:


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>function mergesort!(array, lt = <, low = 1, high = length(array), tmp=similar(array, 0))
<syntaxhighlight lang="julia">function mergesort!(array, lt = <, low = 1, high = length(array), tmp=similar(array, 0))
high <= low && return array
high <= low && return array
middle = low + div(high - low, 2)
middle = low + div(high - low, 2)
Line 585: Line 883:
testmergesort("forever julia programming language")
testmergesort("forever julia programming language")
testmergesort("Now is the time for all good men to come to the aid of their country.", false)
testmergesort("Now is the time for all good men to come to the aid of their country.", false)
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
Unsorted -> forever julia programming language
Unsorted -> forever julia programming language
Line 594: Line 892:


=== case insensitive quicksort ===
=== case insensitive quicksort ===
<lang julia>function qsort(array)
<syntaxhighlight lang="julia">function qsort(array)
length(array) < 2 && return array
length(array) < 2 && return array
mid, left, right = first(array), eltype(array)[], eltype(array)[]
mid, left, right = first(array), eltype(array)[], eltype(array)[]
Line 612: Line 910:
testqsort("forever julia programming language")
testqsort("forever julia programming language")
testqsort("Now is the time for all good men to come to the aid of their country.")
testqsort("Now is the time for all good men to come to the aid of their country.")
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
Unsorted -> forever julia programming language
Unsorted -> forever julia programming language
Line 619: Line 917:
Sorted -> .aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy
Sorted -> .aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy
</pre>
</pre>

=== alphabet-only counting version ===
<syntaxhighlight lang="julia">
const alphabets = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"

function lettercountingsort(s)
sorted = Char[]
for l in alphabets
append!(sorted, fill(l, count(==(l), s)))
end
return String(sorted)
end

println(lettercountingsort("Now is the time for all good men to come to the aid of their country."))
</syntaxhighlight>{{out}}
<pre>
aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy
</pre>

=={{header|K}}==
{{works with|ngn/k}}<syntaxhighlight lang=K>{x@<_x}"This is a test"
" aehiisssTtt"
{x@<_x}"The sentence \"The quick brown fox jumps over the lazy dog\" uses every letter of the alphabet."
" \"\".aaabbccdeeeeeeeeeeeeeeffghhhhhijklllmnnnoooooppqrrrrssssTtTtttttuuuvvwxyyz"
{x@<x}"This is a test" / remove the _ to sort in ascii order rather than alphabetic order
" Taehiissstt"</syntaxhighlight>
=={{header|Lua}}==
<syntaxhighlight lang="lua">fcoll = {} -- forward collation
sl = string.lower -- for case insensitivity
for i=0,255 do fcoll[i]=string.char(i) end -- initially just ASCII (for non-letters)
table.sort(fcoll, function(a,b) return sl(a)==sl(b) and a<b or sl(a)<sl(b) end) -- interleave upper/lower letters
rcoll = {} for i,v in ipairs(fcoll) do rcoll[v]=i end -- reverse collation

function sort(s) -- Latin letters lexicographically, uppercase first, anything else by ASCII
local t={} s:gsub("(%S)", function(c) t[#t+1]=c end) -- use "(.)" as pattern to preserve whitespace
table.sort(t, function(a,b) return rcoll[a]<rcoll[b] end)
return table.concat(t)
end

print(sort("Now is the time for all good men to come to the aid of their country."))</syntaxhighlight>
{{out}}
<pre>.aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy</pre>
Concise version, implicit rather than explicit collation sequence table, adequate for this use, same output:
<syntaxhighlight lang="lua">function sort(s) -- Latin letters lexicographically, uppercase first, anything else by ASCII
local sl,t=string.lower,{} s:gsub("(%S)", function(c) t[#t+1]=c end) -- use "(.)" as pattern to preserve whitespace
table.sort(t, function(a,b) return sl(a)==sl(b) and a<b or sl(a)<sl(b) end) -- implicitly
return table.concat(t)
end

print(sort("Now is the time for all good men to come to the aid of their country."))</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>sortstring = Characters /* LexicographicSort /* StringJoin;
<syntaxhighlight lang="mathematica">sortstring = Characters /* LexicographicSort /* StringJoin;
sortstring["Now is the time for all good men to come to the aid of their country."]</lang>
sortstring["Now is the time for all good men to come to the aid of their country."]</syntaxhighlight>
{{out}}
{{out}}
<pre>". aaccddeeeeeeffghhhiiiillmmmnnNooooooooorrrstttttttuwy"</pre>
<pre>". aaccddeeeeeeffghhhiiiillmmmnnNooooooooorrrstttttttuwy"</pre>


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import strutils, tables
<syntaxhighlight lang="nim">import strutils, tables


func sorted(text: string; omitSpaces = false): string =
func sorted(text: string; omitSpaces = false): string =
Line 636: Line 984:


echo sorted("The quick brown fox jumps over the lazy dog, apparently", false)
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)</lang>
echo sorted("Now is the time for all good men to come to the aid of their country.", true)</syntaxhighlight>


{{out}}
{{out}}
<pre> ,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz
<pre> ,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy</pre>
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy</pre>

=={{header|Pascal}}==
{{works with|Extended Pascal}}
In Pascal it is guaranteed that all letters of the Modern English alphabet, <tt>'A'</tt> through <tt>'Z'</tt> and <tt>'a'</tt> through <tt>'z'</tt>, are in alphabetical order.
That means <tt>ord('A')&nbsp;<&nbsp;ord('B')</tt>.
However, uppercase and lowercase letters may be separate (like in ASCII), fully or partially interspersed.
The output of this program may differ in that regard.
<syntaxhighlight lang="pascal">program sortTheLettersOfStringInAlphabeticalOrder(input, output);

type
line = string(80);

{
sort characters in a string
\param sample the string to sort
\return \param sample so for all n < m: sample[n] <= sample[m]
}
function alphabeticallySorted(sample: line): line;
var
c: char;
{ `sample.capacity` refers to 80 in this program. }
i: 0..sample.capacity;
{ `… value [otherwise 0]` is an initial state specification. }
tab: array[char] of 0..sample.capacity value [otherwise 0];
begin
{ analyze: how many occurrences of every character? }
for i := 1 to length(sample) do
begin
tab[sample[i]] := tab[sample[i]] + 1
end;
{ process: rebuild string but in alphabetical order }
sample := '';
for c := chr(0) to maxChar do
begin
for i := 1 to tab[c] do
begin
sample := sample + c
end
end;
{ finish: set result variable }
alphabeticallySorted := sample
end;

{ === MAIN =================================================== }
var
s: line;
begin
while not EOF do
begin
readLn(s);
writeLn(alphabeticallySorted(s))
end
end.</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>#!/usr/bin/perl -l
<syntaxhighlight lang="perl">#!/usr/bin/perl -l


use strict; # https://rosettacode.org/wiki/Sort_the_letters_of_string_in_alphabitical_order
use strict; # https://rosettacode.org/wiki/Sort_the_letters_of_string_in_alphabitical_order
Line 679: Line 1,084:
1 while s/(.)(.)(??{$1 le $2 && '(*FAIL)'})/$2$1/g;
1 while s/(.)(.)(??{$1 le $2 && '(*FAIL)'})/$2$1/g;
return $_;
return $_;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 706: Line 1,111:
=={{header|Phix}}==
=={{header|Phix}}==
Not sure this algorithm actually ''has'' a name, but it certainly ain't the fastest, though it possibly ''is'' just about the shortest...<br><small>(If pressed I would dub this "Unoptimised bubble sort without the swapped flag")</small>
Not sure this algorithm actually ''has'' a name, but it certainly ain't the fastest, though it possibly ''is'' just about the shortest...<br><small>(If pressed I would dub this "Unoptimised bubble sort without the swapped flag")</small>
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">string_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">string_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 723: Line 1,128:
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Now is the time for all good men to come to the aid of their country."</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Now is the time for all good men to come to the aid of their country."</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Original:\"%s\",\n Sorted:\"%s\"\n Builtin:\"%s\"\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">string_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Original:\"%s\",\n Sorted:\"%s\"\n Builtin:\"%s\"\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">string_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 732: Line 1,137:
===case insensitive===
===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.<br><small>(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.)</small>
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.<br><small>(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.)</small>
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">string_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">string_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 752: Line 1,157:
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Now is the time for all good men to come to the aid of their country."</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Now is the time for all good men to come to the aid of their country."</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"baNAnaBAnaNA"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (just to be awkward)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"baNAnaBAnaNA"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (just to be awkward)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 763: Line 1,168:
</pre>
</pre>
Should you want/prefer the output of baNAnaBAnaNA to be AAAaaaBaNNnn, change the test (leaving the builtin/cia as an exercise) to
Should you want/prefer the output of baNAnaBAnaNA to be AAAaaaBaNNnn, change the test (leaving the builtin/cia as an exercise) to
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">while</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">2</span> <span style="color: #008080;">and</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sj</span><span style="color: #0000FF;">)<</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">or</span> <span style="color: #000000;">sj</span><span style="color: #0000FF;">=</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">32</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">2</span> <span style="color: #008080;">and</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sj</span><span style="color: #0000FF;">)<</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">or</span> <span style="color: #000000;">sj</span><span style="color: #0000FF;">=</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">32</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
Or of course for aaaAAAbBnnNN use
Or of course for aaaAAAbBnnNN use
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">while</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">2</span> <span style="color: #008080;">and</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sj</span><span style="color: #0000FF;">)<</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">or</span> <span style="color: #000000;">sj</span><span style="color: #0000FF;">-</span><span style="color: #000000;">32</span><span style="color: #0000FF;">=</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">2</span> <span style="color: #008080;">and</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sj</span><span style="color: #0000FF;">)<</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">or</span> <span style="color: #000000;">sj</span><span style="color: #0000FF;">-</span><span style="color: #000000;">32</span><span style="color: #0000FF;">=</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">do</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|Python}}==
=={{header|Python}}==
<lang python>'''Sorted string'''
<syntaxhighlight lang="python">'''Sorted string'''


from functools import reduce
from functools import reduce
Line 828: Line 1,233:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>" ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"</pre>
<pre>" ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"</pre>

=={{header|Quackery}}==

With regard to the [[Talk:Sort the letters of string in alphabetical order|discussion]] regarding the nature of the task, I am construing the phrases "alphabetical order" and "lexicographical order" to mean QACSFOT order. ('''''Q'''uackery '''A'''rbitrary '''C'''haracter '''S'''equence '''F'''or '''O'''rdered '''T'''ext'')

We take the 96 printable characters that Quackery recognises in their native (ASCII/Unicode) order, and sort them into QACSFOT order using a word <code>qacsort</code> that we have defined to do that.

<syntaxhighlight lang="Quackery"> [ sortwith [ qacsfot dip qacsfot > ] ] is qacsort ( $ --> $ )

[] 94 times [ i^ 1+ space + join ]

say "Native order:" cr
dup echo$ cr cr
say "QACSFOT order:" cr
qacsort echo$</syntaxhighlight>

{{out}}

<pre>Native order:
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

QACSFOT order:
0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz()[]{}<>~=+-*/^\|_.,:;?!'"`%@&#$</pre>


=={{header|Raku}}==
=={{header|Raku}}==
===Semi-realistic version===
===Semi-realistic version===
<lang perl6>sub sort_within_string ( $_ is copy ) {
<syntaxhighlight lang="raku" line>sub sort_within_string ( $_ is copy ) {
constant @lexographic_order = sort *.fc, map &chr, 1..255;
constant @lexographic_order = sort *.fc, map &chr, 1..255;


Line 847: Line 1,275:
Now is the time for all good men to come to the aid of their country.
Now is the time for all good men to come to the aid of their country.
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 862: Line 1,290:
Sorted output is wrapped in double guillemots to make it easier to see where it starts and ends.
Sorted output is wrapped in double guillemots to make it easier to see where it starts and ends.


<lang perl6>sub moronic-sort ($string is copy) {
<syntaxhighlight lang="raku" line>sub moronic-sort ($string is copy) {
my $chars = $string.chars;
my $chars = $string.chars;
loop {
loop {
Line 889: Line 1,317:


say "\nExtended test string:\n" ~ my $test = (32..126)».chr.pick(*).join;
say "\nExtended test string:\n" ~ my $test = (32..126)».chr.pick(*).join;
say wrap moronic-sort $test;</lang>
say wrap moronic-sort $test;</syntaxhighlight>


{{out}}
{{out}}
Line 909: Line 1,337:


The particular string used is from a typing drill devised by Charles E. Weller in the early 20th century.
The particular string used is from a typing drill devised by Charles E. Weller in the early 20th century.
<lang rexx>/*REXX program sorts an array (of any kind of items) using the bubble─sort algorithm.*/
<syntaxhighlight lang="rexx">/*REXX program sorts an array (of any kind of items) using the bubble─sort algorithm.*/
parse arg y /*generate the array elements (items).*/
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."
if y='' then y= "Now is the time for all good men to come to the aid of their country."
Line 927: Line 1,355:
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
make@: parse arg z; #= length(z); do j=1 for #; @.j= substr(z, j, 1); end; return
make@: parse arg z; #= length(z); do j=1 for #; @.j= substr(z, j, 1); end; return
makeS: parse arg a; $=; do j=1 for #; $= $ || @.j; end; return</lang>
makeS: parse arg a; $=; do j=1 for #; $= $ || @.j; end; return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 935: Line 1,363:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
see "working..." + nl
see "working..." + nl
see "Sort the letters of string in alphabitical order:" + nl
see "Sort the letters of string in alphabitical order:" + nl
Line 954: Line 1,382:
see "Output: " + str + nl
see "Output: " + str + nl
see "done..." + nl
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 962: Line 1,390:
Output: aaaeeefgggggiilmmnnnooprrrrruv
Output: aaaeeefgggggiilmmnnnooprrrrruv
done...
done...
</pre>

=={{header|RPL}}==
{{works with|HP|48G}}
≪ { }
1 3 PICK SIZE '''FOR''' j
OVER j DUP SUB + '''NEXT'''
SWAP DROP
SORT ∑LIST
≫ '<span style="color:blue">STRORT</span>' STO

"The quick brown fox jumps over the lazy dog, apparently" <span style="color:blue">STRORT</span>
{{out}}
<pre>
1: " ,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz"
</pre>

=={{header|VBScript}}==
VBScript can't index a string so first we convert the string to an array of chars, then use join to get back a string
<syntaxhighlight lang="vb">
sub bubble(arr)
n = UBound(arr)
Do
nn = -1
For j = 0 to n - 1
If arr(j) > arr(j + 1) Then
temp= arr(j):arr(j)=arr(j+1):arr(j+1)=temp
nn = j
End If
Next
n = nn
Loop Until nn = -1
end sub


s="The quick brown fox jumps over the lazy dog, apparently"
redim a(len(s)-1)
for i=1 to len(s)
a(i-1)=mid(s,i,1)
next
bubble a
s1=join(a,"")
wscript.echo s1
</syntaxhighlight>
{{out}}
<pre>
,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz
</pre>
</pre>


=={{header|Wren}}==
=={{header|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.
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.
<lang ecmascript>var bubbleSort = Fn.new { |s, trim| // allow optional removal of whitespace
<syntaxhighlight lang="wren">var bubbleSort = Fn.new { |s, trim| // allow optional removal of whitespace
var chars = s.toList
var chars = s.toList
var n = chars.count
var n = chars.count
Line 991: Line 1,466:
System.print(["Unsorted->" + str[0], "Sorted ->" + bubbleSort.call(str[0], str[1])].join("\n"))
System.print(["Unsorted->" + str[0], "Sorted ->" + bubbleSort.call(str[0], str[1])].join("\n"))
System.print()
System.print()
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,003: Line 1,478:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>string 0; \use zero-terminated strings
<syntaxhighlight lang="xpl0">string 0; \use zero-terminated strings


func StrLen(Str); \Return number of characters in an ASCIIZ string
func StrLen(Str); \Return number of characters in an ASCIIZ string
Line 1,025: Line 1,500:
Text(0, Sort("Pack my box with five dozen liquor jugs."));
Text(0, Sort("Pack my box with five dozen liquor jugs."));
CrLf(0);
CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 1,032: Line 1,507:
.Pabcdeefghiiijklmnoooqrstuuvwxyz
.Pabcdeefghiiijklmnoooqrstuuvwxyz
</pre>
</pre>


=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Sort_the_letters_of_string_in_alphabetical_order
// by Galileo, 04/2022

sub Sorted$(t$)
local chars(255), c, i, j, r$
for i = 1 to len(t$)
c = asc(mid$(t$, i, 1))
chars(c) = chars(c) + 1
next
for i = 32 to 126
c = chars(i)
if c then
for j = 1 to c
r$ = r$ + chr$(i)
next
end if
next
return r$
end sub


text$ = "Sort the letters of string in alphabitical order."

print text$
print Sorted$(text$)</syntaxhighlight>
{{out}}
<pre>Sort the letters of string in alphabitical order.
.Saaabcdeeeefghhiiiilllnnoooprrrrrsstttttt
---Program done, press RETURN---</pre>

Latest revision as of 11:10, 8 February 2024

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.


Task

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.

11l

F sorted_str(s)
   DefaultDict[Char, Int] d
   L(c) s
      d[c]++
   V r = ‘’
   L(k) sorted(d.keys())
      r ‘’= k * d[k]
   R r

print(sorted_str(‘The quick brown fox jumps over the lazy dog, apparently’))
print(sorted_str(‘Is this misspelling of alphabetical as alphabitical a joke ?’))
Output:
         ,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz
         ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt

Action!

INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit

PROC Test(CHAR ARRAY s)
  PrintF("Original:%E""%S""%E%E",s)
  SortB(s+1,s(0),0)
  PrintF("Sorted:%E""%S""%E%E",s)
RETURN

PROC Main()
  Put(125) PutE() ;clear the screen
  Test("The quick brown fox jumps over the lazy dog, apparently")
  Test("Now is the time for all good men to come to the aid of their country.")
RETURN
Output:

Screenshot from Atari 8-bit computer

Original:
"The quick brown fox jumps over the lazy dog, apparently"

Sorted:
"         ,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz"

Original:
"Now is the time for all good men to come to the aid of their country."

Sorted:
"               .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy"

Ada

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!
                                    !,,.AIRWaaaaaaaaaabbcccddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeefffgggggggghhhhhhhhhhiiiiiiiiiiiiiikllllllllmmmmmmmmmnnnnnnnnnnnnnoooooooooprrrrrrrrrrrrrrrrssssssssssstttttttttttttttuuuuuuvwwwyyy

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

ALGOL W

Sorts the letters, leaving the non-letters unsorted.

begin
    % returns s with the letters sorted                           %
    %         as Algol W doesn't have variable length strings,    %
    %         the number of characters to sort must be specified  %
    %         in len                                              %
    string(256) procedure lSort( string(256) value s; integer value len ) ;
    begin
        string(256) letters, sortedS;
        integer lLen, lPos, u;
        sortedS := s;
        % get the letters %
        letters := "";
        lLen    := -1;
        for i := 0 until len - 1 do begin
            string(1) c;
            c := s( i // 1 );
            if ( c >= "a" and c <= "z" ) or ( c >= "A" and c <= "Z" ) then begin
                lLen := lLen + 1;
                letters( lLen // 1 ) := c
            end if_we_have_a_letter
        end for_i ;
        % bubble sort the letters %
        u := lLen;
        while begin
            logical sorted;
            sorted := true;
            u      := u - 1;
            for p := 0 until u do begin
                string(1) c, d;
                c := letters( p     // 1 );
                d := letters( p + 1 // 1 );
                if c > d then begin
                    letters( p     // 1 ) := d;
                    letters( p + 1 // 1 ) := c;
                    sorted                := false
                end if_c_gt_d
            end for_p ;
            not sorted
        end do begin end;
        % put the sorted letters into the result string %
        lPos := -1;
        for i := 0 until len - 1 do begin
            string(1) c;
            c := s( i // 1 );
            if ( c >= "a" and c <= "z" ) or ( c >= "A" and c <= "Z" ) then begin
                lpos := lPos + 1;
                sortedS( i // 1 ) := letters( lPos // 1 )
            end if_we_have_a_letter
        end for_i ;
        sortedS
    end lSort ;
    % prints the first len characters of s %
    procedure writeOnString( string(256) value s; integer value len ) ;
        for i := 0 until len - 1 do writeon( s_w := 0, s( i // 1 ) );
    % tests the lSort procedure %
    procedure testSort( string(256) value s; integer value len ) ;
    begin
        writeon( s_w := 0, "    [" );writeOnString(        s, len );        writeon( "]" );write();
        writeon( s_w := 0, " -> [" );writeOnString( lSort( s, len ), len ); writeon( "]" );write()
    end testSort ;

    testSort( "The quick brown fox jumps over the lazy dog, apparently", 55 );
    testSort( "Now is the time for all good men to come to the aid of their country.", 69 );
    testSort( "Stop! In the name of Wuv!", 25 )
end.
Output:
    [The quick brown fox jumps over the lazy dog, apparently]
 -> [Taa abcde eeefg hhi jkllm nnoo oop ppqr rrs, ttuuvwxyyz]
    [Now is the time for all good men to come to the aid of their country.]
 -> [Naa cc dde eeee eff ghh hiii ill mm mnno oo ooo ooo rr rsttt ttttuwy.]
    [Stop! In the name of Wuv!]
 -> [ISWa! ee fhm nnoo pt tuv!]

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

AutoHotkey

sortLetters(str, RemoveSpace := 1){
    oChar := []
    for i, v in StrSplit(str)
        if (v <> " ") && RemoveSpace
            oChar[Asc(v), i] := v
        else if !RemoveSpace
            oChar[Asc(v), i] := v
        
    for ascii, obj in oChar
        for i, letter in obj
            result .= letter
    return result
}

Examples:

str1 := "The quick brown fox jumps over the lazy dog, apparently"
str2 := "Now is the time for all good men to come to the aid of their country."

MsgBox, 262144, , % result := str1 " ->`n" sortLetters(str1)
                . "`n`n" str2 " ->`n" sortLetters(str2, 0)
Output:
The quick brown fox jumps over the lazy dog, apparently ->
,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz

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.AWK
BEGIN {
    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

#include <stdio.h>

/* Sort a character string in place */
void strsort(char *s) {
    unsigned int n[256] = {0};
    unsigned char i = 0;
    char *t = s;
    while (*s) ++n[(unsigned char) *s++];
    while (++i) while (n[i]--) *t++ = (char) i;
}

int main() {
    char s[] = "Now is the time for all good men "
               "to come to the aid of their country.";
    puts(s);
    strsort(s);
    puts(s);
    return 0;
}
Output:
Now is the time for all good men to come to the aid of their country.
               .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy

C++

#include <algorithm>
#include <iostream>

int main() {
    std::string s = "Now is the time for all good men "
                    "to come to the aid of our country.";
    
    std::cout << s << std::endl;
    std::sort(s.begin(), s.end());
    std::cout << s << std::endl; 
    return 0;
}
Output:
Now is the time for all good men to come to the aid of our country.
               .Naaccddeeeeeffghhiiillmmmnnoooooooooorrrsttttttuuwy

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...

CLU

% Unicode is explicitly not supported, the standard says
% that "every implementation must provide at least 128,
% but no more than 512, characters".
% That means we can do it in O(N) using a counting sort.

sort_string = proc (s: string) returns (string)
    char_count: array[int] := array[int]$fill(0,512,0)
    for c: char in string$chars(s) do
        i: int := char$c2i(c)
        char_count[i] := char_count[i]+1
    end
    
    sorted_chars: array[char] := array[char]$predict(1,string$size(s))
    for i: int in array[int]$indexes(char_count) do
        for j: int in int$from_to(1,char_count[i]) do
            array[char]$addh(sorted_chars, char$i2c(i))
        end
    end
    
    return(string$ac2s(sorted_chars))
end sort_string

start_up = proc ()
    po: stream := stream$primary_output()
    str: string := "Now is the time for all good men to come to the aid of their country."
    
    stream$putl(po, str)
    stream$putl(po, sort_string(str))
end start_up
Output:
Now is the time for all good men to come to the aid of their country.
               .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy

Comal

0010 PROC strsort(REF s$) CLOSED
0020   DIM count#(0:255)
0030   FOR i#:=1 TO LEN(s$) DO count#(ORD(s$(i#))):+1
0040   i#:=1
0050   FOR j#:=0 TO 255 DO
0060     IF count#(j#)>0 THEN
0070       s$(i#:i#+count#(j#)-1):=CHR$(j#)*count#(j#)
0080       i#:+count#(j#)
0090     ENDIF
0100   ENDFOR j#
0110 ENDPROC strsort
0120 //
0130 test$:="Now is the time for all good men "
0140 test$:+"to come to the aid of their country."
0150 PRINT test$
0160 strsort(test$)
0170 PRINT test$
0180 END
Output:
Now is the time for all good men to come to the aid of their country.
               .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy

Common Lisp

(sort "Now is the time for all good men to come to the aid of their country." #'char<=)
Output:
"               .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy"


Delphi

Works with: Delphi version 6.0

Uses Delphi TStringList component to do most of the heavy lifting. The TStringList is designed to hold and maniputlate strings. In the strings are one character long so it sorts characters from the strings.

function SortStringLetters(S: string): string;
{Extract letters from string and sort them}
{Uses string list component to hold and sort chars}
var SL: TStringList;
var I: integer;
begin
SL:=TStringList.Create;
try
for I:=1 to Length(S) do SL.Add(S[I]);
SL.Sort;
SetLength(Result,SL.Count);
for I:=0 to SL.Count-1 do
 Result[I+1]:=SL[I][1];
finally SL.Free; end;
end;

const S1 = 'Now is the time for all good men to come to the aid of the party.';
const S2 = 'See the quick brown fox jump over the lazy dog.';

procedure ShowSortedLetters(Memo: TMemo);
var S: string;
begin
Memo.Lines.Add('Unsorted = '+S1);
Memo.Lines.Add('Sorted = '+SortStringLetters(S1));
Memo.Lines.Add('Unsorted = '+S2);
Memo.Lines.Add('Sorted = '+SortStringLetters(S2));
end;
Output:
Unsorted = Now is the time for all good men to come to the aid of the party.
Sorted =                .aaacddeeeeeeffghhhiiillmmmNnooooooooprrstttttttwy
Unsorted = See the quick brown fox jump over the lazy dog.
Sorted =          .abcdeeeeefghhijklmnoooopqrrSttuuvwxyz

Elapsed Time: 5.996 ms.

Draco

/* Sort a string in place, using a counting sort. */
proc nonrec stringsort(*char str) void:
    [256] word counts;
    byte i;
    word j;
    char c;
    channel input text chi;
    channel output text cho;
    
    /* zero array */
    for i from 0 upto 255 do counts[i] := 0 od;
    
    /* count all characters */
    open(chi, str);
    while read(chi; c) do counts[c] := counts[c] + 1 od;
    close(chi);
    
    /* write the characters back in order */
    open(cho, str);
    for i from 0 upto 255 do
        for j from 1 upto counts[i] do
            write(cho; pretend(i, char))
        od
    od;
    close(cho)
corp

/* Test */
proc nonrec main() void:
    *char s;
    s := "Now is the time for all good men to come to the aid of their country.";
    
    writeln(s);
    stringsort(s);
    writeln(s)
corp
Output:
Now is the time for all good men to come to the aid of their country.
               .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy

Eiffel

Example Code

class
	SORT_STRING_LETTERS

feature -- Basic Ops

	sort_string (s: STRING): STRING
			-- Perform `sort_string' on `s' such that
			--	each letter is in ascending alphabetical order.
		note
			deviation: "[
				This Eiffel example deviates from the task requirement for this
				Rosetta Code task in that we reuse Eiffel Base library code for
				the {SORTED_TWO_WAY_LIST [G]}. We do this for two very good reasons:
				
				1. Reuse is king. Never code what is already coded and tested.
				2. The library code is readily available for examination
					(i.e. the library code is not hidden and unaccessible).
					
				Based on #1 and #2 above, examine the code in: {SORTED_TWO_WAY_LIST}.make_from_iterable
				Specifically, look at the `extend' routine and the routines it calls (i.e. `search_after',
				`put_left', and `back'). These routines will tell you the story of how sorting can
				be coded in Eiffel. There is no need to rehash that code here.
				]"
		local
			l_list: SORTED_TWO_WAY_LIST [CHARACTER]
		do
			create l_list.make_from_iterable (s)			-- Add & Auto-sort string by chars
			create Result.make_empty				-- Create the Result STRING
			 c:l_list ¦ Result.append_character (c) 		-- Populate it with the sorted chars
			Result.adjust						-- Remove the leading white space
		ensure
			no_spaces:  c:Result ¦ c /= ' '			-- All spaces removed.
			has_all:  c:Result ¦ s.has (c)				-- All non-space chars present.
			valid_count: Result.count =
					(s.count - s.occurrences (' '))		-- Every character (even repeating).
		end

end

Notice the use of Design-by-Contract in the "ensure" at the end of `sort_string'. At testing runtime, we want the routine itself to ensure that the resulting string has no space character and that every character that we passed in the `s' argument is represented in the result string. We even go so far as to ensure that repeating characters are all represented. We could go further, but we felt these contracts were sufficient to get the point of Design-by-Contract across to you as the reader.

Also note the unicode characters of ⟳ .. ⟲ and ∀. These are called across-loops and we have used the "symbolic form" of them. The first one simply says, "Across all items in l_list as c, perform the code between the ¦ and closing ⟲. In the case of the ∀, this is a loop stating that every member of the Result STRING must hold true for the Boolean expression. For example, in the "no_spaces" contract, we are saying that each character "c" must not be equal to a space (e.g. ' ').

And the Test Code to operate it.

Test Code

class
	RC_SORT_STRING_LETTERS_TEST_SET

inherit
	TEST_SET_SUPPORT

feature -- Test routines

	rc_sort_string_letters_test
			-- Test {SORT_STRING_LETTERS}.
		note
			testing:
				"covers/{SORT_STRING_LETTERS}",
				"execution/isolated",
				"execution/serial"
		do
			assert_strings_equal ("sorted", now_is_string, item.sort_string ("Now is the time for all good men to come to the aid of their country."))
		end

feature {NONE} -- Test Support

	now_is_string: STRING = "[
.Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy
]"

	item: SORT_STRING_LETTERS
			-- An `item' for testing.
		once
			create Result
		end

end

F#

// Alphabetic sort. Nigel Galloway: July 27th., 2021
let 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

FreeBASIC

function value( s as string ) as integer
    'maps a=A=0, b=B=1, etc
    return asc(ucase(s))-65
end function

sub sortstr( ins as string, outs as string )
    dim as string c
    dim as integer cv, i, j
    outs = ""
    for i = 1 to len(ins)
        c = mid(ins,i,1)
        cv = value(c)
        if cv > 25 or cv < 0 then continue for   'this isn't a letter so don't output it
        for j = 1 to len(outs)
            if value(mid(outs,j,1))>cv then exit for
        next j
        outs = left(outs,j-1) + c + right(outs,len(outs)-j+1)
    next i
end sub

dim as string example = "Once upon a midnight dreary as I pondered weak and weary over many a dumb and buggy line of irritating code"
dim as string sorted

sortstr( example, sorted )
print sorted
Output:
aaaaaaaaaabbccddddddddeeeeeeeeefgggghiiIiiiiklmmmnnnnnnnnnOooooopprrrrrrrstttuuuvwwyyyy


FutureBasic

local fn AlphabetizeString( string as CFStringRef, deleteSpaces as BOOL ) as CFStringRef
  NSUInteger  i, count
  CFStringRef tempStr, alphaStr = NULL
  CFArrayRef  array
  
  if deleteSpaces then tempStr = fn StringByReplacingOccurrencesOfString( string, @" ", @"" ) else tempStr = string
  count = fn StringLength( tempStr )
  
  CFMutableArrayRef mutArr = fn MutableArrayWithCapacity(count)
  for i = 0 to count -1
    CFStringRef chr = fn StringWithFormat( @"%C", fn StringCharacterAtIndex( tempStr, i ) )
    MutableArrayInsertObjectAtIndex( mutArr, chr, i )
  next
  array = fn ArraySortedArrayUsingSelector( mutArr, @"localizedCaseInsensitiveCompare:" )
  alphaStr = fn ArrayComponentsJoinedByString( array, @"" )
end fn = alphaStr

CFStringRef testStr

testStr = @"The quick brown fox jumped over the lazy dog's back."
print testStr
print "String alphabetized with spaces included:"
print fn AlphabetizeString( testStr, NO )
print
testStr = @"Now is the time for all good men to come to the aid of their country."
print testStr
print "String alphabetized with spaces deleted:"
print fn AlphabetizeString( testStr, YES )

HandleEvents
Output:
The quick brown fox jumped over the lazy dog's back.
String alphabetized with spaces included:
         .'aabbccddeeeefghhijkklmnoooopqrrsTtuuvwxyz

Now is the time for all good men to come to the aid of their country.
String alphabetized with spaces deleted:
.aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy


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

Haskell

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 Int
charCounts =
  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"

J

J's builtin is 'grade' and sort is a derived function whose domain includes sequences of characters, so:

   text0=: 'This is a test'
   text1=: 'The sentence "The quick brown fox jumps over the lazy dog" uses every letter in the alphabet.'
   /:~ text0
   Taehiissstt
   /:~ text1
                "".TTaaabbccdeeeeeeeeeeeeeefghhhhhiijklllmnnnnooooppqrrrrssssttttttuuuvvwxyyz

However, sorting characters is easy to implement using bucket sort:

   {{a.#~<:#/.~a.,y}} text0
   Taehiissstt
   {{a.#~<:#/.~a.,y}} text1
                "".TTaaabbccdeeeeeeeeeeeeeefghhhhhiijklllmnnnnooooppqrrrrssssttttttuuuvvwxyyz

(Since there's no comparison between pairs in bucket sort, performance here is O(n) rather than O(n log n).)

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 array
end

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

alphabet-only counting version

const alphabets = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"

function lettercountingsort(s)
    sorted = Char[]
    for l in alphabets
       append!(sorted, fill(l, count(==(l), s)))
    end
    return String(sorted)
end

println(lettercountingsort("Now is the time for all good men to come to the aid of their country."))
Output:
aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy

K

Works with: ngn/k
{x@<_x}"This is a test"
"   aehiisssTtt"
{x@<_x}"The sentence \"The quick brown fox jumps over the lazy dog\" uses every letter of the alphabet."
"                \"\".aaabbccdeeeeeeeeeeeeeeffghhhhhijklllmnnnoooooppqrrrrssssTtTtttttuuuvvwxyyz"
{x@<x}"This is a test"  / remove the _ to sort in ascii order rather than alphabetic order
"   Taehiissstt"

Lua

fcoll = {} -- forward collation
sl = string.lower -- for case insensitivity
for i=0,255 do fcoll[i]=string.char(i) end -- initially just ASCII (for non-letters)
table.sort(fcoll, function(a,b) return sl(a)==sl(b) and a<b or sl(a)<sl(b) end) -- interleave upper/lower letters
rcoll = {} for i,v in ipairs(fcoll) do rcoll[v]=i end -- reverse collation

function sort(s) -- Latin letters lexicographically, uppercase first, anything else by ASCII
  local t={} s:gsub("(%S)", function(c) t[#t+1]=c end) -- use "(.)" as pattern to preserve whitespace
  table.sort(t, function(a,b) return rcoll[a]<rcoll[b] end)
  return table.concat(t)
end

print(sort("Now is the time for all good men to come to the aid of their country."))
Output:
.aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy

Concise version, implicit rather than explicit collation sequence table, adequate for this use, same output:

function sort(s) -- Latin letters lexicographically, uppercase first, anything else by ASCII
  local sl,t=string.lower,{} s:gsub("(%S)", function(c) t[#t+1]=c end) -- use "(.)" as pattern to preserve whitespace
  table.sort(t, function(a,b) return sl(a)==sl(b) and a<b or sl(a)<sl(b) end) -- implicitly
  return table.concat(t)
end

print(sort("Now is the time for all good men to come to the aid of their country."))

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

Pascal

Works with: Extended Pascal

In Pascal it is guaranteed that all letters of the Modern English alphabet, 'A' through 'Z' and 'a' through 'z', are in alphabetical order. That means ord('A') < ord('B'). However, uppercase and lowercase letters may be separate (like in ASCII), fully or partially interspersed. The output of this program may differ in that regard.

program sortTheLettersOfStringInAlphabeticalOrder(input, output);

type
	line = string(80);

{
	sort characters in a string
	
	\param sample the string to sort
	\return \param sample so for all n < m: sample[n] <= sample[m]
}
function alphabeticallySorted(sample: line): line;
var
	c: char;
	{ `sample.capacity` refers to 80 in this program. }
	i: 0..sample.capacity;
	{ `… value [otherwise 0]` is an initial state specification. }
	tab: array[char] of 0..sample.capacity value [otherwise 0];
begin
	{ analyze: how many occurrences of every character? }
	for i := 1 to length(sample) do
	begin
		tab[sample[i]] := tab[sample[i]] + 1
	end;
	
	{ process: rebuild string but in alphabetical order }
	sample := '';
	
	for c := chr(0) to maxChar do
	begin
		for i := 1 to tab[c] do
		begin
			sample := sample + c
		end
	end;
	
	{ finish: set result variable }
	alphabeticallySorted := sample
end;

{ === MAIN =================================================== }
var
	s: line;
begin
	while not EOF do
	begin
		readLn(s);
		writeLn(alphabeticallySorted(s))
	end
end.

Perl

#!/usr/bin/perl -l

use strict; # https://rosettacode.org/wiki/Sort_the_letters_of_string_in_alphabitical_order
use warnings;

my @lines = split /\n/, <<END;
The quick brown fox jumps over the lazy dog, apparently
Now 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
  ghiinorrsssttt
  ghiinorrsssttt
  ghiinorrsssttt

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 -> String
def 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"

Quackery

With regard to the discussion regarding the nature of the task, I am construing the phrases "alphabetical order" and "lexicographical order" to mean QACSFOT order. (Quackery Arbitrary Character Sequence For Ordered Text)

We take the 96 printable characters that Quackery recognises in their native (ASCII/Unicode) order, and sort them into QACSFOT order using a word qacsort that we have defined to do that.

  [ sortwith [ qacsfot dip qacsfot > ] ] is qacsort ( $ --> $ )

  [] 94 times [ i^ 1+ space + join ]

  say "Native order:" cr
  dup echo$ cr cr
  say "QACSFOT order:" cr
  qacsort echo$
Output:
Native order:
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

QACSFOT order:
0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz()[]{}<>~=+-*/^\|_.,:;?!'"`%@&#$

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, apparently
Now 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:
»»AabBCcDdEeFfGghHiIjJkKLlMmnNoOpPqQRrSsTtuUVvwWxXyYZz[@\.{=> 1/$(*%&9^57")`'<;6}#42~0:!+,_8?3-]|««

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 make@    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<=@.k  then iterate      /*elements in order? */
           _= @.j;  @.j= @.k;  @.k= _;     ok= 0 /*swap two elements;  flag as not done.*/
           end   /*j*/
         end     /*m*/;               return
/*──────────────────────────────────────────────────────────────────────────────────────*/
make@: parse arg z;  #= length(z);    do j=1  for #;  @.j= substr(z, j, 1);  end;   return
makeS: 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..." + nl
see "Sort the letters of string in alphabitical order:" + nl
str = "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
    next
next

str = substr(str," ","")
see "Output: " + str + nl
see "done..." + nl
Output:
working...
Sort the letters of string in alphabitical order:
Input: forever ring programming language
Output: aaaeeefgggggiilmmnnnooprrrrruv
done...

RPL

Works with: HP version 48G
≪ { } 
   1 3 PICK SIZE FOR j
      OVER j DUP SUB + NEXT
   SWAP DROP
   SORT ∑LIST
≫ 'STRORT' STO
"The quick brown fox jumps over the lazy dog, apparently" STRORT
Output:
1: "         ,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz"

VBScript

VBScript can't index a string so first we convert the string to an array of chars, then use join to get back a string

sub bubble(arr)
  n = UBound(arr)
  Do
    nn = -1
    For j = 0 to n - 1
        If arr(j) > arr(j + 1) Then
            temp= arr(j):arr(j)=arr(j+1):arr(j+1)=temp
           nn = j
        End If
    Next
    n = nn
  Loop Until nn = -1
end sub


s="The quick brown fox jumps over the lazy dog, apparently"
redim a(len(s)-1)
for i=1 to len(s)
   a(i-1)=mid(s,i,1)
next
bubble a
s1=join(a,"")
wscript.echo s1
Output:
         ,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz

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 string
char    Str;
int     I;
for I:= 0 to -1>>1 do
        if Str(I) = 0 then return I;

func Sort(Str);         \Bubble sort string Str
char 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


Yabasic

// Rosetta Code problem: http://rosettacode.org/wiki/Sort_the_letters_of_string_in_alphabetical_order
// by Galileo, 04/2022

sub Sorted$(t$)
    local chars(255), c, i, j, r$
    
    for i = 1 to len(t$)
        c = asc(mid$(t$, i, 1))
        chars(c) = chars(c) + 1
    next
    
    for i = 32 to 126
        c = chars(i)
        if c then
            for j = 1 to c
                r$ = r$ + chr$(i)
            next
        end if
    next
    
    return  r$
end sub


text$ = "Sort the letters of string in alphabitical order."

print text$
print Sorted$(text$)
Output:
Sort the letters of string in alphabitical order.
       .Saaabcdeeeefghhiiiilllnnoooprrrrrsstttttt
---Program done, press RETURN---