Sort a String Array/Slice in Go Language
Hello everyone, In this tutorial, we will show you how to Sort a String Array/Slice Alphabetically in Go Language.
Example 1: Sort a String Slice Alphabetically
// Golang program to demonstrate the
// example of sort.Strings() Method
package main
import (
"fmt"
"sort"
)
func main() {
strarray := []string{"Zeebra", "Lion",
"Ant", "Tiger",
"Hen", "Snake"}
fmt.Println("Before Sort:", strarray)
sort.Strings(strarray)
fmt.Println("After Sort:", strarray)
}
Output:
Example 2: Sort a String Array Alphabetically
// Sort a String Array Alphabetically
package main
import (
"fmt"
"strings"
)
func main() {
strarray := [6]string{"Zeebra", "Lion",
"Ant", "Tiger",
"Hen", "Snake"}
fmt.Println("Before Sort:", strarray)
fmt.Println("After Sort:", Sort(strarray))
}
func Sort(str [6]string) [6]string {
for i := 0; i < len(str)-1; i++ {
for j := i + 1; j < len(str); j++ {
if strings.Compare(str[i], str[j]) > 0 {
temp := str[i]
str[i] = str[j]
str[j] = temp
}
}
}
return str
}
Output:
Example 3: Sort the Slice Elements in Reverse Order
// Sort the Slice Elements in Reverse Order
package main
import (
"fmt"
"sort"
)
func main() {
strarray := []string{"Snake", "Lion",
"Ant", "Tiger",
"Hen", "Zeebra"}
fmt.Println("Before Sort:", strarray)
sort.Sort(sort.Reverse(sort.StringSlice(strarray)))
fmt.Println("After Sort:", strarray)
}
Output:
Example 4: Sort the Array Elements in Reverse Order
// Sort the Array Elements in Reverse Order
package main
import (
"fmt"
"strings"
)
func main() {
strarray := [6]string{"Snake", "Lion",
"Ant", "Tiger",
"Hen", "Zeebra"}
fmt.Println("Before:", strarray)
fmt.Println("After:", Reverse(strarray))
}
func Reverse(str [6]string) [6]string {
for i := 0; i < len(str)-1; i++ {
for j := i + 1; j < len(str); j++ {
if strings.Compare(str[i], str[j]) < 0 {
temp := str[i]
str[i] = str[j]
str[j] = temp
}
}
}
return str
}