How to Reverse Sort a Slice of Integers in Go?

Linda Hamilton
Release: 2024-11-12 11:51:02
Original
802 people have browsed it

How to Reverse Sort a Slice of Integers in Go?

Reverse Sorting a Slice of Integers in Go

You seek to reverse-sort a slice of integers in Go, similar to how the built-in sort.Ints function sorts them from lowest to highest.

Custom Implementation:

You attempted to utilize sort.Ints followed by sort.Reverse, but encountered an error. The issue is that sort.Ints returns a value that cannot be used as a sort.Interface.

IntSlice Type:

The sort package conveniently provides IntSlice, a predefined type that implements the sort.Interface. By using this type, you can achieve reverse sorting with ease. Here's how to accomplish it:

package main

import (
    "fmt"
    "sort"
)

func main() {
    keys := []int{3, 2, 8, 1}
    sort.Sort(sort.Reverse(sort.IntSlice(keys)))
    fmt.Println(keys)
}
Copy after login

This code sorts the slice keys in reverse order, effectively from highest to lowest. The output will be:

[8 3 2 1]
Copy after login

The above is the detailed content of How to Reverse Sort a Slice of Integers in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template