Golang Sort Slice [Ascending & Descending Order]


Tuan Nguyen

GO

Slice is a lightweight data structure that is more effective, adaptable, and convenient than an array in the Go programming language. The slice is a variable-length sequence that holds elements of the same kind; multiple types of components cannot be stored in the same slice. In this tutorial, we will provide some examples of sorting a slice which contains basic types (string, int, float64) using sort package.

The below functions in sort package can be used to sort basic types slices:

func Slice(x any, less func(i, j int) bool): Slice sorts the slice x given the provided less function. It panics if x is not a slice. The sort is not guaranteed to be stable: equal elements may be reversed from their original order. For a stable sort, use SliceStable.

func Sort(data Interface): Sort sorts data in ascending order as determined by the Less method. It makes one call to data.Len to determine n and O(n*log(n)) calls to data.Less and data.Swap. The sort is not guaranteed to be stable.

type StringSlice []string: StringSlice attaches the methods of Interface to []string, sorting in increasing order.

type IntSlice []int: IntSlice attaches the methods of Interface to []int, sorting in increasing order.

type Float64Slice []float64: Float64Slice implements Interface for a []float64, sorting in increasing order, with not-a-number (NaN) values ordered before other values.

 

Example 1: Using Slice() function to sort string, int, float64 slices in ascending order

In example 1, we will use Slice() function to sort string, int and float64 slices in ascending order

Fist of all, we define the Less() function:

func(i, j int) bool {
    return a[i] < a[j]
}

With a is the slice

package main

import (
	"fmt"
	"sort"
)

func main() {
	// int slice
	intSlice := []int{1, 13, 5, 2, 8, 11}
	fmt.Println("Before sort: ", intSlice)
	sort.Slice(intSlice, func(i, j int) bool {
		return intSlice[i] < intSlice[j]
	})

	fmt.Println("After sort:", intSlice)

	// string slice
	stringSlice := []string{"anna", "grey", "mono", "bob", "daniel", "alice"}
	fmt.Println("Before sort: ", stringSlice)
	sort.Slice(stringSlice, func(i, j int) bool {
		return stringSlice[i] < stringSlice[j]
	})

	fmt.Println("After sort:", stringSlice)

	// float64 slice
	floatSlice := []float64{5.4, 2.4, 7.5, 1.5, 6.4}
	fmt.Println("Before sort: ", floatSlice)
	sort.Slice(floatSlice, func(i, j int) bool {
		return floatSlice[i] < floatSlice[j]
	})

	fmt.Println("After sort:", floatSlice)
}

Output:

Before sort:  [1 13 5 2 8 11]
After sort: [1 2 5 8 11 13]
Before sort:  [anna grey mono bob daniel alice]
After sort: [alice anna bob daniel grey mono]
Before sort:  [5.4 2.4 7.5 1.5 6.4]
After sort: [1.5 2.4 5.4 6.4 7.5]

 

Example 2: Using Sice() function to sort string, int, float64 slices in descending order

In example 1, we will use Slice() function to sort string, int and float64 slices in descending order

We need to change the Less() function to:

func(i, j int) bool {
    return a[i] > a[j]
}

With a is the slice

package main

import (
	"fmt"
	"sort"
)

func main() {
	// int slice
	intSlice := []int{1, 13, 5, 2, 8, 11}
	fmt.Println("Before sort: ", intSlice)
	sort.Slice(intSlice, func(i, j int) bool {
		return intSlice[i] > intSlice[j]
	})

	fmt.Println("After sort:", intSlice)

	// string slice
	stringSlice := []string{"anna", "grey", "mono", "bob", "daniel", "alice"}
	fmt.Println("Before sort: ", stringSlice)
	sort.Slice(stringSlice, func(i, j int) bool {
		return stringSlice[i] > stringSlice[j]
	})
        fmt.Println("After sort: ", stringSlice)
}

Output:

Before sort:  [1 13 5 2 8 11]
After sort: [13 11 8 5 2 1]
Before sort:  [anna grey mono bob daniel alice]
After sort:  [mono grey daniel bob anna alice]

 

Example 3: Using Sort() function with StringSlice, IntSlice, Float64Slice interface to ascending sort slices

Here's an example of using Sort() function which takes StringSlice, IntSlice, Float64Slice interfaces as parameter:

package main

import (
	"fmt"
	"sort"
)

func main() {
	// int slice
	intSlice := []int{1, 13, 5, 2, 8, 11}
	fmt.Println("Before sort: ", intSlice)
	sort.Sort(sort.IntSlice(intSlice))

	fmt.Println("After sort:", intSlice)

	// string slice
	stringSlice := []string{"anna", "grey", "mono", "bob", "daniel", "alice"}
	fmt.Println("Before sort: ", stringSlice)
	sort.Sort(sort.StringSlice(stringSlice))

	fmt.Println("After sort:", stringSlice)

	// float64 slice
	floatSlice := []float64{5.4, 2.4, 7.5, 1.5, 6.4}
	fmt.Println("Before sort: ", floatSlice)
	sort.Sort(sort.Float64Slice(floatSlice))

	fmt.Println("After sort:", floatSlice)
}

Output:

Before sort:  [1 13 5 2 8 11]
After sort: [1 2 5 8 11 13]
Before sort:  [anna grey mono bob daniel alice]
After sort: [alice anna bob daniel grey mono]
Before sort:  [5.4 2.4 7.5 1.5 6.4]
After sort: [1.5 2.4 5.4 6.4 7.5]

 

Example 3: Using Sort and Reverse function to descending sort slices

func Reverse(data Interface) Interface: Reverse returns the reverse order for data.

Here's an example of using Sort() and Reverse() function to sort the slice in descending order:

package main

import (
	"fmt"
	"sort"
)

func main() {
	// int slice
	intSlice := []int{1, 13, 5, 2, 8, 11}
	fmt.Println("Before sort: ", intSlice)
	sort.Sort(sort.Reverse(sort.IntSlice(intSlice)))

	fmt.Println("After sort:", intSlice)

	// string slice
	stringSlice := []string{"anna", "grey", "mono", "bob", "daniel", "alice"}
	fmt.Println("Before sort: ", stringSlice)
	sort.Sort(sort.Reverse(sort.StringSlice(stringSlice)))

	fmt.Println("After sort:", stringSlice)

	// float64 slice
	floatSlice := []float64{5.4, 2.4, 7.5, 1.5, 6.4}
	fmt.Println("Before sort: ", floatSlice)
	sort.Sort(sort.Reverse(sort.Float64Slice(floatSlice)))

	fmt.Println("After sort:", floatSlice)
}

Output:

Before sort:  [1 13 5 2 8 11]
After sort: [13 11 8 5 2 1]
Before sort:  [anna grey mono bob daniel alice]
After sort: [mono grey daniel bob anna alice]
Before sort:  [5.4 2.4 7.5 1.5 6.4]
After sort: [7.5 6.4 5.4 2.4 1.5]

 

Example 5: Using Strings(), Int(), Float64() to sort slices

func Strings(x []string): Strings sorts a slice of strings in increasing order.

func Ints(x []int): Ints sorts a slice of ints in increasing order.

func Float64s(x []float64): Float64s sorts a slice of float64s in increasing order. Not-a-number (NaN) values are ordered before other values.

The example below show how to use Ints() and Strings() functions in Golang:

package main

import (
	"fmt"
	"sort"
)

func main() {
	intSl := []int{5, 2, 6, 3, 1, 4} // unsorted
	sort.Ints(intSl)
	fmt.Println(intSl)

	stringSl := []string{"alice", "clair", "ace", "daniel", "bob"} // unsorted
	sort.Strings(stringSl)
	fmt.Println(stringSl)
}

Output:

[1 2 3 4 5 6]
[ace alice bob clair daniel]

 

Summary

I've provided examples of sorting slices in Golang in this article. We can sort slices containing both basic and complex data types with the help of sort package and its functions. Since the slice is sorted in-place, a copy of the sorted slice is not returned.

 

References

https://pkg.go.dev/sort

 

Views: 41

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on LinkedIn.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

GoLinuxCloud Logo


We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Programming Languages

JavaScript

Python

Golang

Node.js

Java

Laravel