Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Showing unstable and stable sorting in Ruby.
# Create a array with numbers from 1 to 100 in a random order
ary = (1..100).to_a.shuffle + (1..100).to_a.shuffle
idx = 0
paired = ary.map.with_index { |value| [value, idx += 1] }
# Now the numbers are paired; the first is the random number 1-100 the second is its sequence within the 200 entries
puts paired.inspect
# You'll see many entries with equal first values where the first of them has a higher second (sequence) number, meaning it's out of order now
puts paired.sort { |x, y| x[0] <=> y[0] }.inspect
# Now we sort exclusively on the value, while preserving ordering
# All entries with identical first values should have second values that are also in numerical order
puts paired.sort_by.with_index { |x, i| [x[0], i] }.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment