Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SR-1990] Sort has incorrect result on small collections with NaN values #44599

Open
natecook1000 opened this issue Jul 5, 2016 · 0 comments
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. standard library Area: Standard library umbrella

Comments

@natecook1000
Copy link
Member

Previous ID SR-1990
Radar None
Original Reporter @natecook1000
Type Bug
Environment

swift/master

Additional Detail from JIRA
Votes 0
Component/s Standard Library
Labels Bug
Assignee None
Priority Medium

md5: 1e24ceab6b5543ae4fa3b7ac98bf9564

relates to:

Issue Description:

When sorting an array of floating-point values, an NaN value will "reset" sorting for a collection with fewer than 20 elements.

(swift) var a = Array(stride(from: 20.0, through: 0.0, by: -1.0))
(swift) a[5] = .nan
// a : Array<Double> = [20.0, 19.0, 18.0, 17.0, 16.0, nan, 14.0, 13.0, 12.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0]

(swift) a.prefix(19).sorted()
// r1 : [Double] = [16.0, 17.0, 18.0, 19.0, 20.0, nan, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0]
(swift) a.prefix(20).sorted()
// r2 : [Double] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 16.0, 17.0, 18.0, 19.0, 20.0, nan]

sort() opts into an insertion sort at that size, which uses !(a[i] < a[i - 1]) to test whether an element at i is sorted correctly. Since (NaN < x) is false for all x, that's always true.

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. standard library Area: Standard library umbrella
Projects
None yet
Development

No branches or pull requests

1 participant