Skip to content

Instantly share code, notes, and snippets.

@indifferentalex
Created May 3, 2018 08:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indifferentalex/08a2434192399bcd13042deda73935c5 to your computer and use it in GitHub Desktop.
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
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