Sort the letters of string in alphabetical order: Difference between revisions
(Added Algol 68) |
(→{{header|ALGOL 68}}: typos) |
||
Line 37: | Line 37: | ||
c |
c |
||
END; # SORT # |
END; # SORT # |
||
print( ( LSORT "The quick brown fox |
print( ( LSORT "The quick brown fox jumps over the lazy dog, apparently", newline ) ) |
||
END</lang> |
END</lang> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz |
|||
,Taaabcdeeeefghhijkllnnnoooopppqrrrsttuuvwxyy |
|||
</pre> |
</pre> |
||
Revision as of 17:58, 24 July 2021
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
Heap sort | Merge sort | Patience sort | Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
- 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.
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. <lang algol68>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 ) )
END</lang>
- Output:
,Taaabcdeeeefghhijkllmnnoooopppqrrrsttuuvwxyyz
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. <lang go>package main
import (
"fmt" "strings"
)
func bubbleSort(s string) string {
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 } } return string(chars)
}
func main() {
s := "forever go programming language" s = bubbleSort(s) s = strings.TrimLeft(s, " \t") // get rid of whitespace which will be at the front fmt.Println(s)
}</lang>
- Output:
aaaeeefgggggilmmnnoooprrrruv
REXX
For REXX, it is normally faster to convert an 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. <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).*/ 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</lang>
- 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
<lang 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 </lang>
- Output:
working... Sort the letters of string in alphabitical order: Input: forever ring programming language Output: aaaeeefgggggiilmmnnnooprrrrruv done...
Wren
Well, we'll write a function for a bubble sort which we don't have in Wren-sort because it's normally much slower than the other methods. However, it's fast enough here. <lang ecmascript>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()
}</lang>
- 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