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

Content added Content deleted
m (syntax highlighting fixup automation)
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 123: Line 123:
=={{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 129:


=={{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 141:
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 155:


=={{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 172:
return(str)
return(str)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 180: Line 180:


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


let sortchars(str) be
let sortchars(str) be
Line 200: Line 200:
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 206:


=={{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 224:
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 230:


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


Line 241: Line 241:
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 248:
=={{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 263: Line 263:
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 275:


=={{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 303:
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}}
{{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 309:


=={{header|Comal}}==
=={{header|Comal}}==
<lang comal>0010 PROC strsort(REF s$) CLOSED
<syntaxhighlight lang="comal">0010 PROC strsort(REF s$) CLOSED
0020 DIM count#(0:255)
0020 DIM count#(0:255)
0030 FOR i#:=1 TO LEN(s$) DO count#(ORD(s$(i#))):+1
0030 FOR i#:=1 TO LEN(s$) DO count#(ORD(s$(i#))):+1
Line 326: Line 326:
0160 strsort(test$)
0160 strsort(test$)
0170 PRINT test$
0170 PRINT test$
0180 END</lang>
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 332: Line 332:


=={{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>
Line 341: Line 341:


=={{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 376: Line 376:
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.
Line 385: Line 385:
[https://github.com/ljr1981/rosettacode_answers/blob/main/src/sort_string_letters/sort_string_letters.e Example Code]
[https://github.com/ljr1981/rosettacode_answers/blob/main/src/sort_string_letters/sort_string_letters.e Example Code]


<lang eiffel>
<syntaxhighlight lang="eiffel">
class
class
SORT_STRING_LETTERS
SORT_STRING_LETTERS
Line 424: Line 424:


end
end
</syntaxhighlight>
</lang>


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
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
Line 435: Line 435:
[https://github.com/ljr1981/rosettacode_answers/blob/main/testing/rc_sort_string_letters/rc_sort_string_letters_test_set.e Test Code]
[https://github.com/ljr1981/rosettacode_answers/blob/main/testing/rc_sort_string_letters/rc_sort_string_letters_test_set.e Test Code]


<lang eiffel>
<syntaxhighlight lang="eiffel">
class
class
RC_SORT_STRING_LETTERS_TEST_SET
RC_SORT_STRING_LETTERS_TEST_SET
Line 468: Line 468:


end
end
</syntaxhighlight>
</lang>


=={{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 480: Line 480:
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 488: Line 488:


=={{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 513: Line 513:


sortstr( example, sorted )
sortstr( example, sorted )
print sorted</lang>
print sorted</syntaxhighlight>
{{out}}<pre>aaaaaaaaaabbccddddddddeeeeeeeeefgggghiiIiiiiklmmmnnnnnnnnnOooooopprrrrrrrstttuuuvwwyyyy</pre>
{{out}}<pre>aaaaaaaaaabbccddddddddeeeeeeeeefgggghiiIiiiiklmmmnnnnnnnnnOooooopprrrrrrrstttuuuvwwyyyy</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 561: Line 561:
fmt.Printf("Sorted ->%s\n\n", res)
fmt.Printf("Sorted ->%s\n\n", res)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 573: Line 573:


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


main :: IO ()
main :: IO ()
Line 579: Line 579:
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 585: Line 585:
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 597: Line 597:
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 604: Line 604:
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 621: Line 621:
. 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}}==
=={{header|J}}==
J's builtin is 'grade' and sort is a derived function whose domain includes sequences of characters, so:<lang J> text0=: 'This is a test'
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.'
text1=: 'The sentence "The quick brown fox jumps over the lazy dog" uses every letter in the alphabet.'
/:~ text0
/:~ text0
Taehiissstt
Taehiissstt
/:~ text1
/:~ text1
"".TTaaabbccdeeeeeeeeeeeeeefghhhhhiijklllmnnnnooooppqrrrrssssttttttuuuvvwxyyz</lang>
"".TTaaabbccdeeeeeeeeeeeeeefghhhhhiijklllmnnnnooooppqrrrrssssttttttuuuvvwxyyz</syntaxhighlight>


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


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


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 660: Line 660:
dingbats
dingbats
| (sort_by_codepoints==sort_by_characters)
| (sort_by_codepoints==sort_by_characters)
</lang>produces
</syntaxhighlight>produces
<pre>
<pre>
true
true
Line 668: Line 668:


=={{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 712: Line 712:
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 721: Line 721:


=== 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 739: Line 739:
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 748: Line 748:


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


Line 760: Line 760:


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


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>fcoll = {} -- forward collation
<syntaxhighlight lang="lua">fcoll = {} -- forward collation
sl = string.lower -- for case insensitivity
sl = string.lower -- for case insensitivity
for i=0,255 do fcoll[i]=string.char(i) end -- initially just ASCII (for non-letters)
for i=0,255 do fcoll[i]=string.char(i) end -- initially just ASCII (for non-letters)
Line 778: Line 778:
end
end


print(sort("Now is the time for all good men to come to the aid of their country."))</lang>
print(sort("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>
Concise version, implicit rather than explicit collation sequence table, adequate for this use, same output:
Concise version, implicit rather than explicit collation sequence table, adequate for this use, same output:
<lang lua>function sort(s) -- Latin letters lexicographically, uppercase first, anything else by ASCII
<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
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
table.sort(t, function(a,b) return sl(a)==sl(b) and a<b or sl(a)<sl(b) end) -- implicitly
Line 788: Line 788:
end
end


print(sort("Now is the time for all good men to come to the aid of their country."))</lang>
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 806: Line 806:


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}}
Line 818: Line 818:
However, uppercase and lowercase letters may be separate (like in ASCII), fully or partially interspersed.
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.
The output of this program may differ in that regard.
<lang pascal>program sortTheLettersOfStringInAlphabeticalOrder(input, output);
<syntaxhighlight lang="pascal">program sortTheLettersOfStringInAlphabeticalOrder(input, output);


type
type
Line 867: Line 867:
writeLn(alphabeticallySorted(s))
writeLn(alphabeticallySorted(s))
end
end
end.</lang>
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 906: Line 906:
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 933: Line 933:
=={{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 950: Line 950:
<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 959: Line 959:
===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 979: Line 979:
<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 990: Line 990:
</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 1,055: Line 1,055:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>" ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"</pre>
<pre>" ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"</pre>
Line 1,061: Line 1,061:
=={{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 1,074: Line 1,074:
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 1,089: Line 1,089:
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 1,116: Line 1,116:


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 1,136: Line 1,136:


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 1,154: Line 1,154:
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
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 1,162: Line 1,162:


=={{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 1,181: Line 1,181:
see "Output: " + str + nl
see "Output: " + str + nl
see "done..." + nl
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,193: Line 1,193:
=={{header|VBScript}}==
=={{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
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">
<lang vb>
sub bubble(arr)
sub bubble(arr)
n = UBound(arr)
n = UBound(arr)
Line 1,217: Line 1,217:
s1=join(a,"")
s1=join(a,"")
wscript.echo s1
wscript.echo s1
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,224: Line 1,224:
=={{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="ecmascript">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 1,249: Line 1,249:
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,261: Line 1,261:


=={{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,283: Line 1,283:
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,293: Line 1,293:


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


Line 1,320: Line 1,320:


print text$
print text$
print Sorted$(text$)</lang>
print Sorted$(text$)</syntaxhighlight>
{{out}}
{{out}}
<pre>Sort the letters of string in alphabitical order.
<pre>Sort the letters of string in alphabitical order.