Sort the letters of string in alphabetical order: Difference between revisions
m (added whitespace, corrected a misspelling.) |
(Added Wren) |
||
Line 35: | Line 35: | ||
Output: aaaeeefgggggiilmmnnnooprrrrruv |
Output: aaaeeefgggggiilmmnnnooprrrrruv |
||
done... |
done... |
||
</pre> |
|||
=={{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. |
|||
<lang ecmascript>var bubbleSort = Fn.new { |s| |
|||
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 |
|||
} |
|||
return chars.join() |
|||
} |
|||
var s = "forever wren programming language" |
|||
s = bubbleSort.call(s).trimStart() // get rid of whitespace which will be at the front |
|||
</lang> |
|||
{{out}} |
|||
<pre> |
|||
aaaeeeefggggilmmnnnooprrrrruvw |
|||
</pre> |
</pre> |
Revision as of 16:32, 24 July 2021
- Task
Write a function to sort the letters of string in alphabetical order.
Write the function even your language has a built-in function for it.
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|
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 } return chars.join()
}
var s = "forever wren programming language" s = bubbleSort.call(s).trimStart() // get rid of whitespace which will be at the front </lang>
- Output:
aaaeeeefggggilmmnnnooprrrrruvw