I
I
impressive172019-12-08 19:10:02
go
impressive17, 2019-12-08 19:10:02

How to sort slice of ints in GO?

Sorting a slice of an int using the sort package. But the output is an unsorted array. Where is the mistake?

package main

import (
  "fmt"
  "sort"
)

func main() {
  var arr = []int{1, 3, 2}
  sort.SliceStable(arr, func(i, j int) bool {
    return i > j
  })
  for _, val := range arr {
    fmt.Println(val)
  }

}

5ded20535fc4b803094672.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Samsonov, 2019-12-08
@impressive17

Sort by index, but you need by value

package main

import (
  "fmt"
  "sort"
)

func main() {
  var arr = []int{1, 3, 2}
  sort.SliceStable(arr, func(i, j int) bool {
    return arr[i] > arr[j]    // здесь поправил
  })
  for _, val := range arr {
    fmt.Println(val)
  }
}

https://play.golang.org/p/49AKa4p7Suf

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question