sort an array in go

To sort an array in Go, we can use the sort package.

Here's an example that sorts an array of integers:

main.go
package main

import (
	"fmt"
	"sort"
)

func main() {
	numbers := []int{4, 2, 1, 5, 3}
	sort.Ints(numbers)
	fmt.Println(numbers)
}
132 chars
13 lines

In this example, we first define an array of integers called numbers. Then we call the sort.Ints() function to sort the array in ascending order. Finally, we print out the sorted array using fmt.Println().

Note that the sort.Ints() function modifies the original array rather than returning a new one, so numbers is now sorted. If you want to sort an array in descending order, you can use the sort.Sort() function with a custom reverse sorting order, like so:

main.go
package main

import (
	"fmt"
	"sort"
)

type reverseInts []int

func (r reverseInts) Len() int {
	return len(r)
}

func (r reverseInts) Swap(i, j int) {
	r[i], r[j] = r[j], r[i]
}

func (r reverseInts) Less(i, j int) bool {
	return r[i] > r[j]
}

func main() {
	numbers := []int{4, 2, 1, 5, 3}
	sort.Sort(reverseInts(numbers))
	fmt.Println(numbers)
}
352 chars
27 lines

In this example, we define a custom type called reverseInts that holds an array of integers. We also define three methods on this type: Len(), Swap(), and Less(). The Len() method returns the length of the array, Swap() swaps two elements in the array, and Less() specifies the reverse sorting order (i.e., it returns true if r[i] is greater than r[j]).

Then we call sort.Sort() with a reverseInts object that wraps the numbers array. This sorts the array in descending order, and we print it out using fmt.Println().

That's it! With the sort package, sorting arrays in Go is easy and efficient.

related categories

gistlibby LogSnag