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:

Popular posts from this blog

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

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example