Home > Backend Development > Golang > How to Reverse-Sort a Slice of Integers in Go?

How to Reverse-Sort a Slice of Integers in Go?

Linda Hamilton
Release: 2024-11-19 16:16:03
Original
893 people have browsed it

How to Reverse-Sort a Slice of Integers in Go?

How to Reverse-Sort a Slice of Integers in Go

In Go, you can encounter the need to reverse-sort a slice of integers, where the highest number is listed first. This is different from the default sorting behavior, which sorts from lowest to highest.

To achieve reverse sorting, you cannot simply combine sort.Ints and sort.Reverse. Using sort.Ints creates a convenience function for sorting a few ints, while sort.Reverse expects a type that implements the sort.Interface interface. However, the sort package provides a predefined type called IntSlice that solves this issue:

Solution:

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

IntSlice is a slice of integers that implements sort.Interface, meaning it can be sorted by its Less method. sort.Reverse creates a new type that reverses the order of Less, effectively providing reverse sorting.

This method allows you to reverse-sort slices of integers efficiently without the need for custom sorting algorithms or complicated interfaces.

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