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
}
Output:

Comments

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

ReactJS - Bootstrap - Buttons

Java - How to Count the Number of Occurrences of Substring in a String

Spring Core | BeanFactoryPostProcessor | Example

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

Custom Exception Handling in Quarkus REST API

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024