Skip to content

Instantly share code, notes, and snippets.

@Snarp
Last active September 30, 2021 16:48
Show Gist options
  • Save Snarp/72d39d3312a832358d0255853da03514 to your computer and use it in GitHub Desktop.
Save Snarp/72d39d3312a832358d0255853da03514 to your computer and use it in GitHub Desktop.
Example Ruby implementations of stable_sort and stable_sort_by
module Enumerable
# Sources:
# - https://stackoverflow.com/a/15442966/797772
# - https://rubygems.org/gems/vex/versions/0.6.2
def stable_sort_by
sort_by.with_index { |x,idx| [yield(x), idx] }
end
# def stable_sort_by
# i=0
# sort_by { |x| [ yield(x), i+=1 ] }
# end
# Sources:
# - https://8thlight.com/blog/will-warner/2013/03/26/stable-sorting-in-ruby.html
# - http://moserei.de/2008/09/18/stable-array-sorting-in-ruby.html
# - https://web.archive.org/web/20081011045822/http://codesnippets.joyent.com/posts/show/19
# Takes a block:
def stable_sort
n = 0
c = lambda { |x| n+=1; [x, n] }
if block_given?
sort { |a, b| yield( c.call(a), c.call(b) ) }
else
sort_by &c
end
end
# # Doesn't take a block:
# def stable_sort
# n = 0
# sort_by { |x| n+= 1; [x, n] }
# end
#
# def stable_sort
# sort_by.with_index { |x, idx| [x, idx] }
# end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment