gopherdata/gophernotes

Strange Behaviour for Custom Sort

xdays opened this issue · 2 comments

xdays commented

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}]

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

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

I will work on it

fixed in commit 5004e48