gopherdata / gophernotes

The Go kernel for Jupyter notebooks and nteract.
MIT License
3.84k stars 265 forks source link

Strange Behaviour for Custom Sort #175

Closed xdays closed 5 years ago

xdays commented 5 years ago

Here's my sort code:

// Custom Sort
import "sort"
import "fmt"
type Person struct {
    First string
    Age   int
}

type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }

func test1() {
    p1 := Person{"James", 32}
    p2 := Person{"Moneypenny", 27}
    p3 := Person{"Q", 64}
    p4 := Person{"M", 56}

    people := []Person{p1, p2, p3, p4}
    fmt.Println(people)
    sort.Sort(ByAge(people))
    fmt.Println(people)
}
test1()

and the result is:

[{James 32} {Moneypenny 27} {Q 64} {M 56}]
[{James 32} {James 32} {Q 64} {Q 64}]

Here's result from playground: https://play.golang.org/p/Upde5QH42LI

and the result is:

[{James 32} {Moneypenny 27} {Q 64} {M 56}]
[{Moneypenny 27} {James 32} {M 56} {Q 64}]
cosmos72 commented 5 years ago

Confirmed. It seems to be a bug in the multiple assignment

a[i], a[j] = a[j], a[i]

I will work on it

cosmos72 commented 5 years ago

fixed in commit 5004e48269c9e3d496fa3435dbf28802682eb799