To sort an array in Go, we can use the sort
package.
Here's an example that sorts an array of integers:
main.go132 chars13 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.go352 chars27 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.
gistlibby LogSnag