Home »
Golang »
Golang Reference
Golang sort.StringsAreSorted() Function with Examples
Golang | sort.StringsAreSorted() Function: Here, we are going to learn about the StringsAreSorted() function of the sort package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 14, 2021
sort.StringsAreSorted()
The StringsAreSorted() function is an inbuilt function of the sort package which is used to check whether the given slice of strings (string type of elements) is sorted in increasing order or not.
It accepts a parameter (x []string) and returns true if x is sorted in ascending order; false, otherwise.
Syntax
func StringsAreSorted(x []string) bool
Parameters
- x : The slice of strings is to be checked whether sorted or not.
Return Value
The return type of the StringsAreSorted() function is a bool, it returns true if the given slice of strings is sorted in ascending order; false, otherwise.
Example 1
// Golang program to demonstrate the
// example of sort.StringsAreSorted() Function
package main
import (
"fmt"
"sort"
)
func main() {
x := []string{"Banana", "Apple", "Cat", "Mango"}
fmt.Println("x:", x)
fmt.Println("sort.StringsAreSorted(x):",
sort.StringsAreSorted(x))
fmt.Println()
x = []string{"City", "Creta", "Tigor", "Venue"}
fmt.Println("x:", x)
fmt.Println("sort.StringsAreSorted(x):",
sort.StringsAreSorted(x))
}
Output:
x: [Banana Apple Cat Mango]
sort.StringsAreSorted(x): false
x: [City Creta Tigor Venue]
sort.StringsAreSorted(x): true
Example 2
// Golang program to demonstrate the
// example of sort.StringsAreSorted() Function
package main
import (
"fmt"
"sort"
)
func main() {
x := []string{"Banana", "Apple", "Cat", "Mango"}
fmt.Println("x:", x)
// Checking whether x is sorted or not,
// if not sorted then sorting the x, and printing
if sort.StringsAreSorted(x) == true {
fmt.Println("Elements are already sorted")
} else {
fmt.Println("Elements are not sorted")
fmt.Println("Sorting....")
sort.Strings(x)
fmt.Println("Sorting done.")
fmt.Println("x:", x)
}
fmt.Println()
x = []string{"City", "Creta", "Tigor", "Venue"}
fmt.Println("x:", x)
// Checking whether x is sorted or not,
// if not sorted then sorting the x
// and printing
if sort.StringsAreSorted(x) == true {
fmt.Println("Elements are already sorted")
} else {
fmt.Println("Elements are not sorted")
fmt.Println("Sorting....")
sort.Strings(x)
fmt.Println("Sorting done.")
fmt.Println("x:", x)
}
}
Output:
x: [Banana Apple Cat Mango]
Elements are not sorted
Sorting....
Sorting done.
x: [Apple Banana Cat Mango]
x: [City Creta Tigor Venue]
Elements are already sorted
Golang sort Package »