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

→‎{{header|Go}}: use built-in sort algorithm
m (→‎{{header|Haskell}}: Used partition for the rough and ready sort)
(→‎{{header|Go}}: use built-in sort algorithm)
Line 82:
 
=={{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.
<lang go>package main
 
import (
"fmt"
"sort"
"strings"
)
 
// type and methods satisfying sort.Interface
func bubbleSort(s string, trim bool) string { // allow optional removal of whitespace
type chars :=runeSlice []rune(s)
func (x runeSlice) Len() int { return len(x) }
n := len(chars)
func (x runeSlice) Less(i, j int) bool { return x[i] < x[j] }
for {
func (x runeSlice) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
n2 := 0
 
for i := 1; i < n; i++ {
func bubbleSortsortLettersInString(s string, trim bool) string { // allow optional removal of whitespace
if chars[i-1] > chars[i] {
tmpchars := chars[i]runeSlice(s)
sort.Sort(chars[i] = chars[i-1])
chars[i-1] = tmp
n2 = i
}
}
n = n2
if n == 0 {
break
}
}
s = string(chars)
if trim {
Line 122 ⟶ 113:
trims := []bool{true, false}
for i, s := range ss {
res := bubbleSortsortLettersInString(s, trims[i])
fmt.Printf("Unsorted->%s\n", s)
fmt.Printf("Sorted ->%s\n\n", res)
Anonymous user