Instantly share code, notes, and snippets.

Embed
What would you like to do?
Potentially unstable ruby sort vs a sort that is guaranteed to be stable
unsorted_array = [21, 12, 47, 41, 33, 11, 13, 31, 43]
puts unsorted_array.sort_by { |n| n.to_s[0] }.to_s
# [12, 13, 11, 21, 33, 31, 47, 43, 41] on Mac OS X,
# [12, 11, 13, 21, 33, 31, 47, 41, 43] on most Linux distributions
puts unsorted_array.sort_by.with_index { |n, i| [n.to_s[0], i] }.to_s
# [12, 11, 13, 21, 33, 31, 47, 41, 43] even on Mac OS X, stability achieved!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment