Skip to content

Instantly share code, notes, and snippets.

@cyberfox
Created January 31, 2011 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cyberfox/803842 to your computer and use it in GitHub Desktop.
Save cyberfox/803842 to your computer and use it in GitHub Desktop.
Showing unstable and stable sorting in Ruby.
# This example is flawed, but hopefully useful for demonstration purposes.
def test_stable_sorting
ary = (1..100).to_a.shuffle + (1..100).to_a.shuffle
# This associates an ordering with the randomized numbers
idx = 0
paired = ary.collect {|value| [value, idx += 1]}
puts "Now the numbers are paired; the first is the random number 1-100,"
puts "the second is its sequence within the 200 entries."
puts paired.inspect
puts
puts "#sort is unstable; you'll see many entries with equal first values"
puts "where the first of them has a higher second (sequence) number, meaning"
puts "it's out of order now."
puts paired.sort {|x,y| x.first <=> y.first }.inspect
puts
puts "Now we sort exclusively on the value, while preserving ordering;"
puts "All entries with identical first values should have second values"
puts "that are also in numerical order."
puts paired.sort_by.with_index {|x, i| [x.first, i]}.inspect
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment