Commit 480ef72c authored by Florian Uekermann's avatar Florian Uekermann Committed by Russ Cox

sort: fixed bug in (Float64Slice) Less; NaN less than anything else

Previously comparisons with NaN led to contradictory results if it was
compared to anything not NaN, since Less always returned false, thus
breaking monotonicity of ordering.
This fix makes NaN less than anything else and adds NaN and (+-)Inf to
testcases.

Fixes #2092.

R=golang-dev, r, rsc, r
CC=golang-dev
https://golang.org/cl/4805051
parent 47410a24
...@@ -6,6 +6,8 @@ ...@@ -6,6 +6,8 @@
// collections. // collections.
package sort package sort
import "math"
// A type, typically a collection, that satisfies sort.Interface can be // A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the // sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index. // elements of the collection be enumerated by an integer index.
...@@ -167,7 +169,7 @@ func (p IntSlice) Sort() { Sort(p) } ...@@ -167,7 +169,7 @@ func (p IntSlice) Sort() { Sort(p) }
type Float64Slice []float64 type Float64Slice []float64
func (p Float64Slice) Len() int { return len(p) } func (p Float64Slice) Len() int { return len(p) }
func (p Float64Slice) Less(i, j int) bool { return p[i] < p[j] } func (p Float64Slice) Less(i, j int) bool { return p[i] < p[j] || math.IsNaN(p[i]) && !math.IsNaN(p[j]) }
func (p Float64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p Float64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// Sort is a convenience method. // Sort is a convenience method.
......
...@@ -6,6 +6,7 @@ package sort_test ...@@ -6,6 +6,7 @@ package sort_test
import ( import (
"fmt" "fmt"
"math"
"rand" "rand"
. "sort" . "sort"
"strconv" "strconv"
...@@ -13,7 +14,7 @@ import ( ...@@ -13,7 +14,7 @@ import (
) )
var ints = [...]int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586} var ints = [...]int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586}
var float64s = [...]float64{74.3, 59.0, 238.2, -784.0, 2.3, 9845.768, -959.7485, 905, 7.8, 7.8} var float64s = [...]float64{74.3, 59.0, math.Inf(1), 238.2, -784.0, 2.3, math.NaN(), math.NaN(), math.Inf(-1), 9845.768, -959.7485, 905, 7.8, 7.8}
var strings = [...]string{"", "Hello", "foo", "bar", "foo", "f00", "%*&^*&^&", "***"} var strings = [...]string{"", "Hello", "foo", "bar", "foo", "f00", "%*&^*&^&", "***"}
func TestSortIntSlice(t *testing.T) { func TestSortIntSlice(t *testing.T) {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment