Created
May 3, 2018 08:10
-
-
Save indifferentalex/08a2434192399bcd13042deda73935c5 to your computer and use it in GitHub Desktop.
Potentially unstable ruby sort vs a sort that is guaranteed to be stable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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